Java 中物件克隆有什麼用?
物件克隆是建立物件精確副本的一種方式。為此,使用物件類的clone()方法來克隆物件。物件的克隆要建立的類必須實現Cloneable介面。如果我們不實現Cloneable介面,clone()方法會生成CloneNotSupportedException。
clone()方法節省了建立物件精確副本的額外處理任務。如果我們使用new關鍵字執行此操作,將需要執行大量處理,因此我們可以使用物件克隆。
語法
protected Object clone() throws CloneNotSupportedException
示例
public class EmployeeTest implements Cloneable { int id; String name = ""; Employee(int id, String name) { this.id = id; this.name = name; } public Employee clone() throws CloneNotSupportedException { return (Employee)super.clone(); } public static void main(String[] args) { Employee emp = new Employee(115, "Raja"); System.out.println(emp.name); try { Employee emp1 = emp.clone(); System.out.println(emp1.name); } catch(CloneNotSupportedException cnse) { cnse.printStackTrace(); } } }
輸出
Raja Raja
廣告