无法将一个类的对象访问到另一个类中

时间:2013-11-07 01:46:47

标签: 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(String[] args) {
        new UDPThread(5002,station).start();
    }  
}         

station是我正在创建类Spb_server的对象,我想在main方法中访问它。但它然后要求我制作我不想要的修饰语static。有什么方法可以实现这个目标吗?

2 个答案:

答案 0 :(得分:0)

如果要从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();
}

答案 1 :(得分:0)

嗯,你必须在某处初始化Spb_server。在这段代码中,在main函数中执行此操作是有意义的,所以像

public static void main(String[] args) {
    Spb_server station = new Spb_server() // Or whatever your constructor is
    new UDPThread(5002,station).start();
}