我有这样的事情:
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的属性也会间接改变吗?
答案 0 :(得分:6)
如果我更改了o4This的属性该怎么办? o4的财产也会 间接改变?
是,它会被更改。因为现在,o4All
和o4This
都指的是同一个实例。您通过以下任务完成此操作: -
Test.o4All = this.o4This;
在上述作业中,您没有创建o4This
引用的实例的副本,而只是在o4This
引用中复制o4All
的值。现在,由于o4This
值是对某些instance
的引用。因此,o4All
现在引用了与o4This
相同的实例。因此,您使用引用对instance
所做的任何更改也会反映在另一个引用中。