【发布时间】:2014-07-14 02:04:38
【问题描述】:
如果您在不同的类中引用一个实例化的对象,更改是否更新为实际对象或只是引用..
public class First {
List<String> numbers;
public First(){
this.numbers.add("one");
this.numbers.add("two");
}
}
public class Second{
First InstanceOfFirst;
public Second(First F){
this.InstanceOfFirst = F;
}
public void printList(){
for(String s : this.InstanceOfFirst.numbers){
System.out.print(i+", ");
}
}
}
public class Third {
First Reference;
public Third(First F){
this.Reference = F;
}
public void Update(){
this.Reference.numbers.add("three");
}
}
所以假设我的主要看起来像这样:
public static main(String args[]){
First F = new Frist();
Second sec = new Second(F);
Third th = new Third(F);
th.Update();
sec.printList();
}
我会因此得到one, two 或one, two, three。
我想我想问的是:Deos Java 在这样引用时会制作不同的对象副本,还是它们指向同一个对象??
如果我的问题似乎含糊不清,请原谅..
【问题讨论】:
-
它们指向同一个对象。你试过运行这个吗?
-
出于这个原因,我更喜欢Call by [Object] Sharing这个词。无论如何,这都有been asked before。
标签: java oop reference pass-by-reference