浅拷贝也会在堆上创建一个对象,但是如果原对象中有引用数据类型,那么拷贝的对象会直接复制其引用数据类型,也就是说,原对象和引用对象共用一个内部对象。
深拷贝会完全复制整个对象,包括原对象中的内部对象。
public class Address implements Cloneable{
private String name;
// 省略构造函数、Getter&Setter方法
@Override
public Address clone() {
try {
return (Address) super.clone();
} catch (CloneNotSupportedException e) {
throw new AssertionError();
}
}
}
public class Person implements Cloneable {
private Address address;
// 省略构造函数、Getter&Setter方法
@Override
public Person clone() {
try {
// 浅拷贝
Person person = (Person) super.clone();
return person;
// 深拷贝
Person person = (Person) super.clone();
person.setAddress(this.address.clone());
return person;
} catch (CloneNotSupportedException e) {
throw new AssertionError();
}
}
}