我有这样的东西:
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 ),我可以使用对象引用。
Class methods cannot access instance variables or instance methods directly—they must use an object reference.
如果我更改 o4This 的属性会怎样? o4All 的属性也会被间接改变吗?
最佳答案
What if I change a property of o4This? Will the property of o4All also be changed indirectly?
是,它会被改变。因为现在,o4All
和 o4This
都指的是同一个实例。您通过以下作业完成了此操作:-
Test.o4All = this.o4This;
在上面的赋值中,您不是在创建 o4This
引用的实例的副本,而是在 中复制
引用。现在,由于 o4This
的值>o4Allo4This
值是对某些 instance
的引用。因此,o4All
现在引用了与 o4This
相同的实例。因此,您使用引用对 instance
所做的任何更改也将反射(reflect)在其他引用中。
关于java - 将实例变量分配给静态变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14778120/