- 现在有三个类 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;
}
}