Object cloning là cách tạo bản sao chính xác của một đối tượng. Dùng phương thức clone() của lớp Object. Interface Cloneable phải được triển khai bởi lớp muốn clone. Nếu không implement Cloneable, clone() ném CloneNotSupportedException.
Phương thức clone() tiết kiệm xử lý tạo bản sao chính xác. Nếu dùng từ khóa new, tốn nhiều xử lý hơn, nên dùng object cloning.
Cú pháp
protected Object clone() throws CloneNotSupportedException
Ví dụ
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();
}
}
}
Kết quả
Raja Raja