深克隆、浅克隆

首先建了一个Wallet类

public class Wallet  {
    private int number;

    public Wallet(int number) {
        this.number = number;
    }

    public int getNumber() {
        return number;
    }

    public void setNumber(int number) {
        this.number = number;
    }
}

然后建了一个Person类

public class Person implements Cloneable{
    private int age;
    private Wallet money;

    public Person(int age, Wallet money) {
        this.age = age;
        this.money = money;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Wallet getMoney() {
        return money;
    }

    public void setMoney(Wallet money) {
        this.money = money;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}

测试代码

    public static void main(String[] args) throws CloneNotSupportedException {
        Wallet wallet = new Wallet(100);
        Person personA = new Person(20, wallet);
        Person personB= (Person) personA.clone();
        System.out.println("B的年纪"+personB.getAge());
        System.out.println("B的钱数" + personB.getMoney().getNumber());
        personB.setAge(50);
        personB.getMoney().setNumber(20);
        System.out.println("A的年纪"+personA.getAge());
        System.out.println("A的钱数" + personA.getMoney().getNumber());
        System.out.println("B的年纪"+personB.getAge());
        System.out.println("B的钱数" + personB.getMoney().getNumber());
    }

输出:
B的年纪20
B的钱数100
A的年纪20
A的钱数20
B的年纪50
B的钱数20

可见clonePerson的时候,Wallet只是copy了指针,并没有copy对象,这就是浅克隆。

在Wallet类中直接加入clone方法

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

输出显示并不能解决问题,依旧是浅克隆。

改一下Person类的clone方法

    @Override
    protected Object clone() throws CloneNotSupportedException {
        Object o = null;
        try {
            o = (Person) super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        ((Person) o).money= (Wallet) money.clone();
        return o;
    }

输出:
B的年纪20
B的钱数100
A的年纪20
A的钱数100
B的年纪50
B的钱数20

可见已经可以用了

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值