话不多说上代码解释深浅克隆:
建立两个对象student和teacher:
public class student implements Serializable,Cloneable{//实现克隆空接口Cloneable
/**
* 序列id
*/
private static final long serialVersionUID = -510341732602471481L;
String name;
Integer ege;
teacher teacher; //含有有一个非基本类型的属性
public student(String name, Integer ege,teacher teacher) {
super();
this.name = name;
this.ege = ege;
this.teacher=teacher;
}
@Override //重写克隆方法-----如果不重写该方法,那么在使用clone()时会报错
protected Object clone() throws CloneNotSupportedException {
return super.clone(); //返回克隆对象
}
}
public class teacher{ //不实现克隆空接口
String tName;
Integer tEge;
public teacher(String tName, Integer tEge) {
super();
this.tName = tName;
this.tEge = tEge;
}
}
测试:
public static void main(String[] args) {
teacher te=new teacher("teacher", new Integer(47));
//初始对象
student stu=new student("ww", new Integer(26),te);
//浅克隆对象
student stud;
try {
stud = (student) stu.clone();//基本类型克隆过去了,引用类型地址一样也克隆过去了,实际上新旧对象的引用属性地址形同
stud.name="ss";
stud.ege=58;
stud.teacher.tName="tansong";
stud.teacher.tEge=69;
System.out.println("旧对象"+stu.name);//旧对象ww
System.out.println("旧对象:"+stu.teacher.tName);//旧对象:tansong 原本值为teacher
System.out.println("克隆对象:"+stud.name);//克隆对象:ss
System.out.println("克隆对象:"+stud.teacher.tName);//克隆对象:tansong
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
深克隆:与浅克隆不同在于,引用属性对象类也实现了Cloneable克隆空接口引用也clone了对象,并重写了clone()方法.。
public class student implements Serializable,Cloneable{
/**
* 序列id
*/
private static final long serialVersionUID = -510341732602471481L;
String name;
Integer ege;
teacher teacher;
public student(String name, Integer ege,teacher teacher) {
super();
this.name = name;
this.ege = ege;
this.teacher=teacher;
}
@Override
protected Object clone() throws CloneNotSupportedException {
student s=null;
s=(student) super.clone();
s.teacher=(serzi.teacher) teacher.clone();
return s;
}
}
public class teacher implements Cloneable{
String tName;
Integer tEge;
public teacher(String tName, Integer tEge) {
super();
this.tName = tName;
this.tEge = tEge;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
直接测试:
public static void main(String[] args) {
teacher te=new teacher("teacher", new Integer(47));
//初始对象
student stu=new student("ww", new Integer(26),te);
//浅克隆对象
student stud;
try {
stud = (student) stu.clone();
stud.name="ss";
stud.ege=58;
stud.teacher.tName="tansong";
stud.teacher.tEge=69;
System.out.println("旧对象"+stu.name);//旧对象ww
System.out.println("旧对象:"+stu.teacher.tName);//旧对象:teacher 原本值为teacher
System.out.println("克隆对象:"+stud.name);//克隆对象:ss
System.out.println("克隆对象:"+stud.teacher.tName);//克隆对象:tansong
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
总结:关于对象的克隆,如果对象含有其他对象那么该对象也必须克隆,否则被克隆对象的引用属性在克隆时仅仅将地址复制一份,而不是重新开辟内存空间。