객체 복제는 객체의 정확한 사본을 만드는 방법입니다. 이를 위해 clone() 객체 클래스의 메소드는 객체를 복제하는 데 사용됩니다. 복제 가능 인터페이스는 생성할 개체 복제가 있는 클래스에 의해 구현되어야 합니다. 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