克隆一个对象
public class CloneDemo implements Cloneable {
int x;
public static void main(String[] args) throws CloneNotSupportedException {
CloneDemo cd = new CloneDemo();
cd.x = 5;
System.out.printf("cd.x = %d%n", cd.x);
CloneDemo cd2 = (CloneDemo) cd.clone();
System.out.printf("cd2.x = %d%n", cd2.x);
}
}
class Data implements Cloneable {
int x;
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
public class CloneDemo {
public static void main(String[] args) throws CloneNotSupportedException {
Data data = new Data();
data.x = 5;
System.out.printf("data.x = %d%n", data.x);
Data data2 = (Data) data.clone();
System.out.printf("data2.x = %d%n", data2.x);
}
}
data.x = 5
data2.x = 5
浅克隆
浅克隆(也叫做浅拷贝)仅仅复制了这个对象本身的成员变量,该对象如果引用了其他对象的话,也不对其复制。
深克隆
深克隆(也叫做深复制)会复制这个对象和它所引用的对象的成员变量,如果该对象引用了其他对象,深克隆也会对其复制。