深度克隆的练习

  • 现在有三个类 FirstLevel 、SecondLevel 、ThirdLevel
    • FirstLevel 类有三个属性

      • int firstIntValue;
        double firstDoubleValue;
        SecondLevel second;
    • SecondLevel 类有三个属性

      • int secondIntValue;
        double secondDoubleValue;
        ThirdLevel third;
    • ThirdLevel 类有两个属性

      • int thirdIntValue;
        double thirdDouleValue
      • 我不是很理解深度clone,这道题的解法是这样的。
public class Demo {
    public static void main(String[] args) throws CloneNotSupportedException {
        FirstLevel first = new FirstLevel(1, 2, new SecondLevel(10, 20, new ThirdLevel(100, 200)));
        FirstLevel cloneFirst = first.clone();

        System.out.println(first.clone().second);
        System.out.println(cloneFirst.clone().second);
    }
}

class FirstLevel  implements Cloneable{
    int firstIntValue;
    double firstDoubleValue;
    SecondLevel second;

    //重写clone方法

    @Override
    protected FirstLevel  clone() throws CloneNotSupportedException {
//        return super.clone();
        FirstLevel  cloneFirst = (FirstLevel )super.clone();
        cloneFirst.second = cloneFirst.second.clone();
        return cloneFirst;
    }

    public FirstLevel (int firstIntValue, double firstDoubleValue, SecondLevel second) {
        this.firstIntValue = firstIntValue;
        this.firstDoubleValue = firstDoubleValue;
        this.second = second;
    }
}

class SecondLevel implements Cloneable{
    int secondIntValue;
    double secondDoubleValue;
    ThirdLevel third;

    //重写clone方法

    @Override
    protected SecondLevel clone() throws CloneNotSupportedException {
//        return super.clone();
        SecondLevel cloneSecond = (SecondLevel) super.clone();
        ThirdLevel cloneThird = this.third.clone();
        cloneSecond.third = cloneThird;
        return cloneSecond;

    }

    public SecondLevel(int secondIntValue, double secondDoubleValue, ThirdLevel third) {
        this.secondIntValue = secondIntValue;
        this.secondDoubleValue = secondDoubleValue;
        this.third = third;
    }
}

class ThirdLevel implements Cloneable{
    int thirdIntValue;
    double thirdDouleValue;

    //重写clone方法


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

    public ThirdLevel(int thirdIntValue, double thirdDouleValue) {
        this.thirdIntValue = thirdIntValue;
        this.thirdDouleValue = thirdDouleValue;
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值