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

时间:2012-07-06 16:00:33

标签: 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());

    }
}

输出结果为:

ONE  
TWO
TWO

应该是:

ONE
ONE
TWO

设备对象非常简单,它只接收两个字符串,第二个是我要求它打印的“名称”。我以前做过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;
}

2 个答案:

答案 0 :(得分:8)

您似乎也使用了static中的Device字段。这些不是实例字段。应避免使用可变static字段。

答案 1 :(得分:0)

来自评论:

  

显示整个Device类。 IP和名称是静态的吗? - assylias 2分钟   前

     

是的,他们是

每当您实例化Device的新实例时,您的设备静态成员都会重新初始化,这就是您获得该行为的原因。您可以将onetwo设为static,但不应该有可变成员变量static

相关问题