深拷贝:进行拷贝后的两个引用分别指向不同对象
class Student implements Cloneable{
String name;
ID id;
public Student(String name, ID id) {
this.name = name;
this.id = id;
}
public Student(String name) {
this.name = name;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
'}';
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
class ID implements Cloneable{
int id;
public ID(int id) {
this.id = id;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
public class Demo01 {
public static void main(String[] args) throws CloneNotSupportedException {
Student stu = new Student("df");
Student stu2 = (Student)stu.clone();
System.out.println(stu.name);
System.out.println(stu2.name);
stu2.name = "DF";
System.out.println(stu.name);
System.out.println(stu2.name);
}
}
修改stu2.name 不会影响stu.name的属性值
若在自定义类型中嵌套自定义类型
Student stu = new Student("df", new ID());
Student stu2 = (Student) stu.clone();
System.out.println(stu.id);
System.out.println(stu2.id);
stu2.id.id=20;
System.out.println(stu.id);
System.out.println(stu2.id);
虽然通过stu.clone得到stu2但是两个对象中的id指向同一个引用。
若要实现完全深拷贝则需要对 ID实现Clonable接口,并重写student中的clone方法
@Override
protected Object clone() throws CloneNotSupportedException {
Student stu = (Student)super.clone();
stu.id = (ID)this.id.clone();
return stu;
}
Student stu = new Student("df", new ID());
Student stu2 = (Student) stu.clone();
System.out.println(stu.id);
System.out.println(stu2.id);
stu2.id.id=20;
System.out.println(stu.id);
System.out.println(stu2.id);