深拷贝:完全开辟出一个新的对象
浅拷贝:引用同一对象的地址
浅拷贝实现:
//默认为浅克隆
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
深拷贝实现:
@Override
protected Object clone() throws CloneNotSupportedException {
Person person = (Person) super.clone();
person.setPhone(new Phone(person.getPhone().getBrand()));
return person;
}
Person类
package test;
import javax.imageio.plugins.jpeg.JPEGImageReadParam;
import java.io.Serializable;
import java.util.Objects;
/**
* @Author 小浩
* @Date 2020/4/2 12:09
* @Version 1.0
**/
public class Person implements Serializable,Cloneable{
Phone phone;
@Override
protected Object clone() throws CloneNotSupportedException {
Person person = (Person) super.clone();
person.setPhone(new Phone(person.getPhone().getBrand()));
return person;
}
public Person(Phone phone) {
this.phone = phone;
}
public Person(){
}
public Phone getPhone() {
return phone;
}
public void setPhone(Phone phone) {
this.phone = phone;
}
@Override
public String toString() {
return "Person{" +
"phone=" + phone +
'}';
}
}
Phone类
package test;
/**
* @Author 小浩
* @Date 2020/4/2 14:23
* @Version 1.0
**/
public class Phone {
private String brand;
public Phone(String brand) {
this.brand = brand;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
@Override
public String toString() {
return "Phone{" +
"brand='" + brand + '\'' +
'}';
}
}
测试类:
package test;
import com.sun.xml.internal.ws.api.model.wsdl.WSDLOutput;
import java.util.*;
/**
* @Author 小浩
* @Date 2020/4/1 19:39
* @Version 1.0
**/
public class Main {
public static void main(String[] args) {
Person p = new Person(new Phone("苹果"));
Person person = null;
try {
person= (Person) p.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
System.out.println(p);
System.out.println(person);
System.out.println("设置其中一个为小米 ");
person.getPhone().setBrand("小米");
System.out.println(p);
System.out.println(person);
}
}
深拷贝输出结果:
浅拷贝输出结果: