JAVA实现深拷贝浅拷贝_Java cloneable接口实现深拷贝和浅拷贝

深拷贝:完全开辟出一个新的对象

浅拷贝:引用同一对象的地址

浅拷贝实现:

//默认为浅克隆

@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);

}

}

深拷贝输出结果:

ce5921f4ad777be1e81d5092c0e8850f.png

浅拷贝输出结果:

66f132815d9b6a1ea688f92c40c27206.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值