public class DrumKitTestDrive {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Echo e1 = new Echo();
Echo e2 = new Echo();
// **e2 = e1;**
int x=0;
while( x < 4 ){
e1.hello();
e1.count = e1.count + 1;
if(x==3){
e2.count = e2.count + 1;
}
if(x>0){
e2.count = e2.count + e1.count;
}
x = x + 1;
}
System.out.print(e2.count);
}
}
class Echo {
int count = 0;
void hello(){
System.out.println("Hellooooo....");
}
}
这段代码的输出将是:
Hellooooo....
Hellooooo....
Hellooooo....
Hellooooo....
10
但是如果我在运行代码时从 //e2= e1;
中删除注释,系统将打印 24 而不是 10 .我不明白为什么会这样?
据我所知,系统只会将 e1
实例的值复制到 e2
实例中。如果系统这样做,结果将保持不变,因为两个对象属于同一类。
最佳答案
What I understand is the system will just copy the values of e1 instance into e2 instance.
不,当您执行 e2 = e1
时,您正在复制对象 references - 您不是在复制对象 - 所以变量 e1
和 e2
都指向同一个对象。
因此,当您进行递增时,它们都会递增相同的计数字段。
只有在没有分配 e2 = e1
时,增量才会发生在两个不同的实例上。
关于java - 当一个对象被分配给另一个对象时会发生什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12020417/