谨慎的覆盖clone()方法

如果一个类实现了Cloneable方法,就可以调用clone方法,并且返回该对象的逐域拷贝,否则抛出cloneNotSupportedException异常。

下面是一个演示clone方法的类,注意深度拷贝问题:


public class testClone implements Cloneable{
inClass in;
public static void main(String[] args) throws CloneNotSupportedException {
   testClone t1=new testClone();
   t1.in=new inClass();
   t1.in.t=10;
   t1.in.tag="obeject1";
   testClone t2=(testClone) t1.clone();
   System.out.println(t1);
   System.out.println(t2);
   t2.in.tag="change";
   System.out.println(t1);
   System.out.println(t2);
}
@Override public String toString(){
   return in.tag+" "+in.t;
}

@Override public testClone clone(){

   try {
    return (testClone) super.clone();
   } catch (CloneNotSupportedException e) {
    throw new AssertionError();
   }
}

}
class inClass{
String tag;
int t;
}
输出结果为:

obeject1 10
obeject1 10
change 10
change 10

原文地址:https://www.cnblogs.com/macula7/p/1960611.html