Java 无法将一个类的对象访问到另一个类
这就是我想要达到的目标Java 无法将一个类的对象访问到另一个类,java,object,methods,constructor,udp,Java,Object,Methods,Constructor,Udp,这就是我想要达到的目标 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(S
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_服务器的对象,我想在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();
}
嗯,您必须在某个地方初始化Spb_服务器。在这段代码中,在main函数中这样做是有意义的,比如
public static void main(String[] args) {
Spb_server station = new Spb_server() // Or whatever your constructor is
new UDPThread(5002,station).start();
}
... 或者在main中的构造函数调用中实例化Spb_服务器:new UDPThread5002,new Spb_server.start;