The following code describes how the cloneable works
You can comment the method clone() and run the app again to find what the differences are.
package org.cxz.clone;
import java.util.concurrent.atomic.AtomicInteger;
public class Target implements Cloneable{
public AtomicInteger num = null;
@Override
protected Object clone() throws CloneNotSupportedException {
Target ret = new Target();
ret.num = new AtomicInteger(num.get());
return ret;
}
public static void main(String[] args){
AtomicInteger oldNumber = new AtomicInteger(100);
Target origin = new Target();
origin.num = oldNumber;
Target cloner = null;
try {
cloner = (Target)origin.clone();
} catch (CloneNotSupportedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
cloner.num.addAndGet(100);
System.out.println(origin.num);
System.out.println(cloner.num);
}
}You can comment the method clone() and run the app again to find what the differences are.
本文介绍了一个实现Cloneable接口的示例,通过覆写clone方法来实现对象的深复制。示例中使用了AtomicInteger类来演示克隆前后对象状态的变化。
9408

被折叠的 条评论
为什么被折叠?



