赋值操作后,对象的引用发生变化

// 此用例来源于Thinking in java
class Tank{
int level;
String msg;
Tmp tmp;
@Override
public String toString() {
return "level = "+level+" msg="+msg+" tmp="+tmp;
}
}
class Tmp{
private String name;
public Tmp(String name){
this.name=name;
}
@Override
public String toString() {
return this.name;
}
}

-----------------
Tank t1 = new Tank();
t1.level =1;
t1.msg="message 1";
t1.tmp = new Tmp("tmp 1");
System.out.println(t1);
Tank t2 = new Tank();
t2.level =2;
t2.msg="message 2";
t2.tmp = new Tmp("tmp 2");
System.out.println(t2);
t1 = t2 ;

t2赋值给t1后,t2中原对象的引用也指向了t1对象的引用,原先t2对象的引用被覆盖,信息丢失。
此时t2与t1指向同一个引用。

你可能感兴趣的:(对象)