自定义类型实现深拷贝

深拷贝:进行拷贝后的两个引用分别指向不同对象

class Student implements Cloneable{
    String name;
    ID id;

    public Student(String name, ID id) {
        this.name = name;
        this.id = id;
    }

    public Student(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                '}';
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}
class  ID implements  Cloneable{
    int id;


    public ID(int id) {
        this.id = id;
    }
    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

}

public class Demo01 {
    public static void main(String[] args) throws CloneNotSupportedException {
        Student stu = new Student("df");
        Student stu2 = (Student)stu.clone();
        System.out.println(stu.name);
        System.out.println(stu2.name);
        stu2.name = "DF";
        System.out.println(stu.name);
        System.out.println(stu2.name);

    }
}

在这里插入图片描述
在这里插入图片描述

修改stu2.name 不会影响stu.name的属性值

若在自定义类型中嵌套自定义类型

Student stu = new Student("df", new ID());
        Student stu2 = (Student) stu.clone();
        System.out.println(stu.id);
        System.out.println(stu2.id);
        stu2.id.id=20;
        System.out.println(stu.id);
        System.out.println(stu2.id);

在这里插入图片描述

在这里插入图片描述

虽然通过stu.clone得到stu2但是两个对象中的id指向同一个引用。

若要实现完全深拷贝则需要对 ID实现Clonable接口,并重写student中的clone方法

  @Override
    protected Object clone() throws CloneNotSupportedException {
        Student stu = (Student)super.clone();
        stu.id = (ID)this.id.clone();
        return stu;
    }


  Student stu = new Student("df", new ID());
        Student stu2 = (Student) stu.clone();
        System.out.println(stu.id);
        System.out.println(stu2.id);
        stu2.id.id=20;
        System.out.println(stu.id);
        System.out.println(stu2.id);

在这里插入图片描述
在这里插入图片描述

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值