public class DeepClone
{
public static void main(String args[]) throws CloneNotSupportedException
{
Student student=new Student();
Teacher teacher=new Teacher();
student.setAge(20);
student.setName("wang xue");
student.setTeacher(teacher);
teacher.setAge(30);
teacher.setName("lucy");
Student stu=(Student)student.clone();
teacher.setName("lily");
System.out.println(stu.getAge()+" "+stu.getName()+" "+stu.getTeacher().getName()+" "+stu.getTeacher().getAge());;
}
}
class Teacher implements Cloneable
{
private int age;
private String name;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public Object clone() throws CloneNotSupportedException {
// TODO Auto-generated method stub
Teacher teacher=(Teacher)super.clone();
return teacher;
}
}
class Student implements Cloneable
{
private Teacher teacher;
private int age;
private String name;
public Teacher getTeacher() {
return teacher;
}
public void setTeacher(Teacher teacher) {
this.teacher = teacher;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public Object clone() throws CloneNotSupportedException {
// TODO Auto-generated method stub
Object object=super.clone();//浅clone
Student stu=(Student)object;
stu.setTeacher((Teacher)stu.getTeacher().clone());//深clone
return stu;
}
}
深度clone的简单实现
最新推荐文章于 2022-07-22 11:37:40 发布