1. 深克隆浅克隆区别
深克隆:将对象依赖的示例也克隆了一份出来
浅克隆:只是克隆当前对象示例,对象所依赖的其他示例则不克隆
2. 代码示例
@Data
public class Teacher implements Cloneable {
private String name;
private int age;
public Teacher(String name, int age){
this.name = name;
this.age = age;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
@Data
public class Student implements Cloneable {
private String name;
private int age;
private Teacher teacher;
public Student(String n, int a, Teacher t){
name = n;
age = a;
teacher = t;
}
@Override
protected Object clone() throws CloneNotSupportedException {
Student student = (Student) super.clone();
// 若没有对teacher进行克隆,则是浅克隆,clone出来的student对象内的teacher实例相同,在内存中指向同一个对象
teacher = (Teacher) teacher.clone();
return student;
}
public static void main(String args[]) throws CloneNotSupportedException {
Teacher t1 = new Teacher("老师1", 45);
Student s1 = new Student("同学1", 15, t1);
Student s2 = (Student) s1.clone();
s2.setName("同学2");
s2.setAge(18);
s2.getTeacher().setName("新老师");
System.out.println(s1);
System.out.println(s2);
}
}