1 需要实现
Cloneabel : public class TestClone implements Cloneable
2 重写clone方法
public Object clone() throws CloneNotSupportedException
{
Object obj = super.clone();
return obj;
}
3 使用
TestClone c = new TestClone();
TestClone b = (TestClone) c.clone();
TestClone d = c;
c.setAge(10);c.setName("QQ");
b.setAge(100);b.setName("father");
d.setAge(80);d.setName("monther");
System.out.println("c="+c.toString());
System.out.println("b="+b.toString());
System.out.println("d="+d.toString());
结果
c=TestClone[name=monther;age=80]
b=TestClone[name=father;age=100]
d=TestClone[name=monther;age=80]
4 说明
c 是原始类,b是clone类,d是引用类;
c和b是双胞胎, d是c的影子;
影子d做的坏事,c也会遭殃;
b做了什么好事与c无关