摘自《编写高质量代码 改善java程序员的151个建议》
对象拷贝的规则如下:
(1)基本类型
如果是变量是基本类型,则拷贝其值,比如int,float等
(2)对象
如果变量是一个实例对象,则拷贝地址引用,也就是说新拷贝出的对象与原有对象共享该实例变量
(3)string字符串
这个比较特殊,拷贝的是一个地址,是个引用,但是在修改时,它会从字符串池中重新生成新的字符串,原有的字符串对象保持不变,我们可以认为string是一个基本类型。
public class Test {
public static void main(String[] args) {
Person father = new Person("父亲", null);
Person son1 = new Person("yi", father);
Person son2 = son1.clone();
son2.setName("er");
son2.getFather().setName("gandie");
System.out.println(son1.getName()+"de father="+son1.getFather().getName());
System.out.println(son2.getName()+"de father="+son2.getFather().getName());
}
}
class Person implements Cloneable {
private String name;
private Person father;
public Person(String name, Person father) {
this(name);
this.father = father;
}
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Person getFather() {
return father;
}
public void setFather(Person father) {
this.father = father;
}
@Override
protected Person clone() {
Person p = null;
try {
p = (Person) super.clone();
p.setFather(new Person(p.getFather().getName()));//实现深拷贝,保证拷贝出来的对象自成一体,不受母体的影响
} catch (CloneNotSupportedException e) {
}
return p;
}
}