深拷贝
在上面代码的基础上,我们修改一下拷贝的逻辑,只需要修改Dog 类和 DogSchool 类。
DogSchool 加上支持拷贝的接口,并且实现接口
public class DogSchool implements Cloneable{
public String address;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
Dog 类里面修改一下拷贝逻辑:
public class Dog implements Cloneable{
public int age;
public String name;
public DogSchool dogSchool;
public Dog(int age, String name){
this.age = age;
this.name = 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;
}
public DogSchool getDogSchool() {
return dogSchool;
}
public void setDogSchool(DogSchool dogSchool) {
this.dogSchool = dogSchool;
}
@Override
public Object clone() throws CloneNotSupportedException {
Dog dog = (Dog)super.clone();
dog.setDogSchool((DogSchool) this.dogSchool.clone());
return dog;
}
}
运行结果:

从浅拷贝我们可以看到只有引用类型会出现指向内存地址是同一个的情况,所以我们处理一下引用类型即可。就达到了深拷贝的效果。
本文介绍了Java中如何实现深拷贝,通过修改Dog和DogSchool类的clone方法,确保引用类型的成员变量也进行拷贝,从而达到深拷贝的效果。例子展示了如何处理引用类型以避免浅拷贝的问题,确保对象的独立性。
https://www.bilibili.com/video/BV1qL411u7eE?spm_id_from=333.337.search-card.all.click&vd_source=3117718bf474f48fd81d26049c0c97ac
16万+

被折叠的 条评论
为什么被折叠?



