解讀:Object中的clone方法爲native,解釋了java的「高效」。實現Cloneable接口的類經過super.clone()調用來實現克隆能力(標準寫法)。克隆是按屬性字段複製的,若是對象的屬性值爲可變的引用(不可變:如基本類型,final類型的,可變:如對象的引用,數組引用),那原對象跟克隆後的對象將沒法保持獨立,由於他們的某個屬性共同引用了一個對象,這就是「淺表複製」,這不是咱們想要的,正常咱們須要的是「深層複製 」,即對對象的屬性進行進一步的clone,for example:
public class A implements Cloneable {
public B b;
public A() {
b = new B();
}
public Object clone() {
A o = null;
try {
o = (A) super.clone();
o.b = (B) b.clone();
//屬性b的克隆,實現A類的深度克隆
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return o;
}
public static void main(String[] args) throws CloneNotSupportedException {
A A_a = new A();
A copyA = A_a;//
copyA.b.setName("i'm copyA from A...");
A cloneA = (A) A_a.clone();
cloneA.b.setName("i'm clone from A...");
System.out.println(cloneA.b.getName());//out :i'm clone from A...
System.out.println(A_a.b.getName());//out :i'm copyA from A...
if (cloneA.equals(A_a)) {
System.out.println("cloneA.equals(A_a) really? no"); //no out
}
if (copyA.equals(A_a)) {
System.out.println("copyA.equals(A_a) -really? yes");//out
}
}
class B implements Cloneable {
String name;
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}