一、浅克隆
1 创建一个基础类Student,拥有birthday(引用数据类型),并让其通过实现Cloneable接口并重写clone方法来实现克隆。
[mw_shl_code=java,true] public class Student implements Cloneable{
private Date birthday;
public Student() {}
public Student(Date birthday) {
this.birthday = birthday;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}[/mw_shl_code]
2 创建一个测试类进行测试,经过克隆后的对象还是不是同一个对象?
[mw_shl_code=java,true]public class CloneTest {
@Test
public void test1() throws CloneNotSupportedException {
Student student1 = new Student(new Date());
Student student2 = (Student) student1.clone();
System.out.println(student1 == student2);
}
}[/mw_shl_code]
dubug结果:
结果分析:
1、这里假设数字就是内存地址:student1的内存地址是850,student2的内存地址是851,他们的内存地址是不同的,所以上述中的比较结果自然是:false
2、但是student1和student2的引用类型属性birthday的内存地址是相同的,原来它仅仅克隆了这个对象最表层的东西,内部的引用类型属性都没改变,所以默认重写的clone方法是一种浅克隆。
二 深克隆
1 在浅克隆的基础上,再次重写clone方法,不仅克隆这个对象本身,还要克隆这个对象中的引用类型属性。
[mw_shl_code=java,true]public class Student implements Cloneable{
private Date birthday;
public Student() {}
public Student(Date birthday) {
this.birthday = birthday;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Override
protected Object clone() throws CloneNotSupportedException {
Student student = (Student) super.clone();
student.birthday = (Date) student.birthday.clone();
return student;
}
}[/mw_shl_code]
dubug结果:
结果分析:
1 student1和student2的引用类型属性birthday的内存地址是相同的,经过再次重写后的clone方法我们称之为深克隆。
|
|