gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 04:12:04 25 4
gpt4 key购买 nike

这就是我想要实现的目标

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com