對象克隆是一種創(chuàng)建對象的精確副本的方法。 Object類的clone()方法用于克隆對象。java.lang.Cloneable接口必須由我們要創(chuàng)建其對象克隆的類實(shí)現(xiàn)。如果我們不實(shí)現(xiàn)Cloneable接口,clone()方法生成CloneNotSupportedException。
clone()方法在Object類中定義。 clone()方法的語法如下:
protected Object clone() throws CloneNotSupportedException
clone()方法保存用于創(chuàng)建對象的精確副本的額外處理任務(wù)。 如果我們使用new關(guān)鍵字執(zhí)行它,它將需要執(zhí)行大量的處理,這就是為什么我們使用對象克隆。
對象克隆的優(yōu)點(diǎn)
讓我們來看看對象克隆的簡單例子
class Student18 implements Cloneable {
int rollno;
String name;
Student18(int rollno, String name) {
this.rollno = rollno;
this.name = name;
}
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
public static void main(String args[]) {
try {
Student18 s1 = new Student18(101, "amit");
Student18 s2 = (Student18) s1.clone();
System.out.println(s1.rollno + " " + s1.name);
System.out.println(s2.rollno + " " + s2.name);
} catch (CloneNotSupportedException c) {
}
}
}
執(zhí)行上面代碼,得到如下結(jié)果 -
101 amit
101 amit
從上面的例子可以看出,兩個(gè)引用變量都有相同的值。 因此,clone()將對象的值復(fù)制到另一個(gè)對象。 因此,在實(shí)際應(yīng)用中我們不需要編寫顯式代碼將對象的值復(fù)制到另一個(gè)對象。
如果通過new關(guān)鍵字創(chuàng)建另一個(gè)對象并將另一個(gè)對象的值賦給這個(gè)對象,則需要對該對象進(jìn)行大量處理。 所以為了節(jié)省額外的處理任務(wù),我們使用clone()方法。