实体类Teacher
public class Teacher implements Cloneable{
private String name ;
public Teacher(String name) {
this.name = name ;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public Teacher clone() throws CloneNotSupportedException {
return (Teacher)super.clone();
}
}
实体类Student
public class Student implements Cloneable{
private String name ;
private int age ;
private Teacher teacher ;
public Student(String name, int age, Teacher teacher) {
this.name = name ;
this.age = age ;
this.teacher = teacher ;
}
@Override
public Student clone() throws CloneNotSupportedException {
Student copy = null ;
copy = (Student)super.clone();
copy.teacher = this.teacher.clone();
return copy ;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Teacher getTeacher() {
return teacher;
}
public void setTeacher(Teacher teacher) {
this.teacher = teacher;
}
}
测试程序
public class CloneTest {
/**
* @param args
*/
public static void main(String[] args) {
Student student = new Student("wujinbo",20,new Teacher("Hello"));
try {
Student copy = student.clone();
//更改数据源的数据
student.setName("冷漠");
student.setAge(100);
student.getTeacher().setName("Hi");
//查看两份数据的差异
System.out.println(student.getName()+"-->"+copy.getName());
System.out.println(student.getAge()+"-->"+copy.getAge());
System.out.println(student.getTeacher().getName()+"-->"+copy.getTeacher().getName());
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
}