
CloneNotSupportedException은 Person 클래스가 Cloneable 인터페이스를 구현하지 않았기 때문입니다.
Person 클래스를 Cloneable 인터페이스를 구현하여 해결할 수 있습니다.
#hostingforum.kr
java
class Person implements Cloneable {
// ...
}
또한, Person 클래스의 clone 메서드에서 super.clone()을 호출하기 전에 객체의 필드를 복사하는 코드를 추가하여 원본 객체의 변경이 복사된 객체에 영향을 미치지 않도록 할 수 있습니다.
#hostingforum.kr
java
@Override
protected Object clone() throws CloneNotSupportedException {
Person copyPerson = (Person) super.clone();
copyPerson.name = this.name;
copyPerson.age = this.age;
return copyPerson;
}
또한, Person 클래스의 필드가 참조 타입인 경우, 참조 타입의 필드를 복사할 때는 clone 메서드를 호출하여 복사해야 합니다.
#hostingforum.kr
java
class Person implements Cloneable {
private String name;
private int age;
private Address address;
public Person(String name, int age, Address address) {
this.name = name;
this.age = age;
this.address = address;
}
@Override
protected Object clone() throws CloneNotSupportedException {
Person copyPerson = (Person) super.clone();
copyPerson.address = (Address) this.address.clone();
return copyPerson;
}
}
Address 클래스 또한 Cloneable 인터페이스를 구현하고 clone 메서드를 구현해야 합니다.
#hostingforum.kr
java
class Address implements Cloneable {
private String street;
private String city;
public Address(String street, String city) {
this.street = street;
this.city = city;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
2025-08-10 12:27