Java Object从另一个实例获取变量?

kak*_*san 1 java oop variables

我不太清楚该怎么称呼它,但实际上,当我运行这段代码时:

public class test {

    static Device one;
    static Device two;

    public static void main(String[] args) throws Exception {

        one = new Device("One", "ONE");
        System.out.println(one.getName());
        two = new Device("Two", "TWO");

        System.out.println(one.getName());
        System.out.println(two.getName());

    }
}
Run Code Online (Sandbox Code Playgroud)

输出是:

ONE  
TWO
TWO
Run Code Online (Sandbox Code Playgroud)

应该是什么时候:

ONE
ONE
TWO
Run Code Online (Sandbox Code Playgroud)

设备对象非常简单,它只接收两个字符串,第二个是我要求它打印的"名称".我以前做过OOP,但我觉得我只是忘记了一些重要的方面,但似乎无法弄明白.任何帮助表示赞赏,谢谢!

这是设备构造函数:

public Device(String iP, String Name) {
    //Set the IP address
    IP = iP;
    //Set the device's name
    name = Name;
    // Set the string version of the device (for transmitting)
    stringVersion = IP + ";" + name;
}
Run Code Online (Sandbox Code Playgroud)

Tom*_*ine 8

看起来你也使用过static字段Device.这些不是实例字段.static应避免可变字段.