clone 메서드를 사용하려면 아래처럼 해야한다는 뜻!
@Override // 1) clone 메서드를 override해서
public PhoneNumber clone() { // 2) public으로 선언해주고
try {
return (PhoneNumber) super.clone(); // 3) Object의 clone 메서드를 호출해주어야한다는 것!
} catch (CloneNotSupportedException e) {
throw new AssertionError();
}
}
복사
의 정확한 뜻은 그 객체를 구현한 클래스에 따라 다를 수 있다.아래 내용에 대한 요구가 반드시 참은 아니다.
// 복사본가 원본이 일치하지 않는다.
x.clone() != x
// 클래스 인스턴스 타입은 같다.
x.clone().getClass() == x.getClass()
아래 일반 식도 일반적으로는 참이지만, 필수는 아니다.
// 동치성
x.clone().equals(x)
관례상, clone()는 super.clone()을 호출해서 반환된 객체를 반환한다.
x.clone().getClass() == x.getClass()
관례상, 반환된 객체와 원본 객체는 독립적이다.
이를 만족하려면 super.clone() 으로 얻은 객체의 필드 중 하나 이상을 반환 전에 수정해야 할 수 있다.
public class Coffee implements Cloneable {
@Override
public synchronized Coffee clone() {
Coffee clone;
try {
clone = (Coffee) super.clone();
} catch (CloneNotSupportedException e) {
throw new AssertionError();
}
return clone;
}
}