深拷贝
在上面代码的基础上,我们修改一下拷贝的逻辑,只需要修改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; } }
运行结果:
从浅拷贝我们可以看到只有引用类型会出现指向内存地址是同一个的情况,所以我们处理一下引用类型即可。就达到了深拷贝的效果。