这就是我想要实现的目标
public class UDPThread extends Thread {
int port;
Spb_server station = null;
public UDPThread(int port, Spb_server station) {
this.port = port;
this.station = station;
}
public static void main(String[] args) {
new UDPThread(5002,station).start();
}
}
<小时/>
station
是我正在创建的类 Spb_server
的对象,我想在 main
方法中访问它。但它随后要求我将修饰符设置为静态,但我不想这样做。有什么办法可以实现这个目标吗?
最佳答案
如果要从main访问,必须将其设为静态。两种可能性:
int port;
static Spb_server station = null;
public UDPThread(int port, Spb_server station)
{
this.port = port;
this.station = station;
}
public static void main(String[] args)
{
new UDPThread(5002,station).start();
}
或局部变量:
int port;
public UDPThread(int port, Spb_server station)
{
this.port = port;
this.station = station;
}
public static void main(String[] args)
{
Spb_server station = null;
new UDPThread(5002,station).start();
}
关于java - 无法将一个类的对象访问到另一个类中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19826491/