《Java基础知识》Java 浅拷贝与深拷贝2

深拷贝

在上面代码的基础上,我们修改一下拷贝的逻辑,只需要修改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;
    }
}

运行结果:

从浅拷贝我们可以看到只有引用类型会出现指向内存地址是同一个的情况,所以我们处理一下引用类型即可。就达到了深拷贝的效果。


尚学堂给同学们带来全新的Java300集课程啦!java零基础小白自学Java必备优质教程_手把手图解学习Java,让学习成为一种享受_哔哩哔哩_bilibiliicon-default.png?t=M5H6https://www.bilibili.com/video/BV1qL411u7eE?spm_id_from=333.337.search-card.all.click&vd_source=3117718bf474f48fd81d26049c0c97ac

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值