public class Computer implements Cloneable{
private String name;
private double price;
public Computer(String name, double price) {
// TODO Auto-generated constructor stu
this.name = name;
this.price = price;
}
@Override
protected Object clone() throws CloneNotSupportedException {
// TODO Auto-generated method stub
return super.clone();
}
public static void main(String[] args) throws CloneNotSupportedException {
// TODO Auto-generated method stub
Computer ct1 = new Computer("dd", 23.2);
Computer ct2 = (Computer) ct1.clone();
ct2.name = "aa";
System.out.println(ct1.name+ct1.price);
System.out.println(ct2.name+ct2.price);
}
}
上面是一个浅克隆的栗子,通过clone()得到了对象的实际值。虽然看上去要比“=”得到的引用更接近,但是实际上跳过了被复制对象本身,而深克隆就更加深入地得到了被复制对象的引用对象。所以可以得到一个复制深度的排序
“=”和参数传递:变量1》》变量2————2 的地址————2的地址的值(常量/变量)…………变量3的地址…………3的地址的地址的值…………4…………5……
浅克隆:变量1》》变量2————2 的地址————2的地址的值(常量/变量3)————变量3的地址————3的地址的地址的值…………4…………5……
深克隆:变量1》》变量2————2 的地址————2的地址的值(常量/变量3)————变量3的地址————3的地址的地址的值————4…………5……
(实线指能够直接指向并复制的地方,之后的部分可以通过引用获得)