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

标签 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 方法中访问它。但它随后要求我将修饰符设置为静态,但我不想这样做。有什么办法可以实现这个目标吗?

最佳答案

如果要从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/

相关文章:

java - Junit参数化设置测试类中的常量

javascript - jquery javascript 从 JSON 对象中删除对象数据

java - Parent 变量如何存储大于 Parent 的 Child?

c# - C# 中的事务

android - 如何覆盖 Phonegap webview 的方法?

java - 如何在 Cassandra 中使用 datastax java 驱动程序有效地使用准备好的语句?

java - 从java中具有多个循环的方法返回单个字符串

java - 使用正则表达式从地址中删除特殊字符

c++ - 通过使用不同的构造函数创建对象并最终释放对象的内存

javascript - 如何将此 API 中的数据转换为由特定 prop 组织的对象数组?