将实例变量分配给静态变量

时间:2013-02-08 17:32:49

标签: java static

我有这样的事情:

public class Test {

    public static MyObject o4All = null;

    public MyObject o4This = null;

    public void initialize() {

        // create an instance of MyObject by constructor
        this.o4This = new MyObject(/* ... */);

        // this works, but I am wondering
        // how o4All is internally created (call by value/reference?)
        Test.o4All = this.o4This;

    }
}

我知道,我应该仅通过静态方法分配或更改静态变量。但根据java-docs(http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html),我可以使用对象引用。

  

类方法不能访问实例变量或实例方法   直接 - 他们必须使用对象引用。

如果我更改了o4This的属性该怎么办? o4All的属性也会间接改变吗?

1 个答案:

答案 0 :(得分:6)

  

如果我更改了o4This的属性该怎么办? o4的财产也会   间接改变?

,它会被更改。因为现在,o4Allo4This都指的是同一个实例。您通过以下任务完成此操作: -

Test.o4All = this.o4This;

在上述作业中,您没有创建o4This引用的实例的副本,而只是在o4This引用中复制o4All的值。现在,由于o4This值是对某些instance的引用。因此,o4All现在引用了与o4This相同的实例。因此,您使用引用对instance所做的任何更改也会反映在另一个引用中。