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

nim*_*o23 2 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;

    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

Roh*_*ain 6

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

是的,它会被改变.因为现在,无论是o4Allo4This指的是同一个实例.你是通过以下任务完成的: -

Test.o4All = this.o4This;
Run Code Online (Sandbox Code Playgroud)

在上面的任务,你是不是创造提到了实例的副本o4This,而是你只是复制的价值o4Thiso4All参考.现在,因为o4This价值是对某些人的参考instance.所以,o4All现在引用与之相同的实例o4This.因此,您对instance使用引用所做的任何更改也将反映在另一个引用中.