Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/362.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 无法将一个类的对象访问到另一个类_Java_Object_Methods_Constructor_Udp - Fatal编程技术网

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;