如果被克隆的 Object 类中包含非原始数据类型,例如另一个类的 Object,则对该对象进行的更改会反映在两个对象中(即原始对象和克隆的对象)?而对原始数据类型进行的更改仅反映在克隆的对象中,为什么呢?
import static java.lang.System.*;
class Best
{
int x;
int y;
}
class Test implements Cloneable
{
int a;
int b;
Best bt = new Best();
public Object clone()throws CloneNotSupportedException
{
return super.clone();
}
}
public class Check
{
public static void main(String [] args) throws CloneNotSupportedException
{
Test t1 = new Test();
t1.a=20;
t1.b=30;
t1.bt.x = 300;
t1.bt.y = 200;
Test t2 = (Test)t1.clone();
t2.a=50; //change reflects only in cloned object
t2.bt.x = 500; //change reflects in both original and cloned object
out.println(t1.a+" "+t1.b+" "+t1.bt.x+" "+t1.bt.y);
out.println(t2.a+" "+t2.b+" "+t2.bt.x+" "+t2.bt.y);
}
}
Java中的深拷贝与浅拷贝
。 - UkFLSUI