본문 바로가기
자바의 메소드 clone()의 기능은 한마디로 복붙. 자신을 복제하여 새로운 인스턴스를 생성한다.
선언부는 protecetd Object clone() 이다.
 
clone()을 쓰려면 몇 가지 조건이 걸린다.
1) 사용하려는 클래스에 Cloneable 인터페이스를 구현해주어야 한다.
2) 사용하려는 클래스 쪽에서 clone()을 오버라이딩하면서 접근 제어자를 public으로 바꿔주어야 한다. (이렇게 해야 상속관계가 없는 다른 클래스에서 clone()을 호출할 수 있다.)
3) 조상클래스의 clone()을 호출하는 코드 super.clone()과 필수 예외처리 CloneNotSupportedException이 포함된 try-catch 문을 작성한다.
public class Pointt implements Cloneable{
    int x,y;
    Pointt (int x, int y) {
        this.x = x;
        this.y = y;
    }
    public String toString() {
        return "x = " +x+ ", y = " + y;
    }
    public Pointt clone() {
        Object obj = null;
        try {
            obj = super.clone();
        } catch(CloneNotSupportedException e) {}
        return (Pointt) obj;
}}
class CloneEx1 {
    public static void main(String[] args) {
        Pointt original = new Pointt(2,1);
        Pointt copy = original.clone();
        System.out.println(original +" 복제!! "+ copy);
    }
}

실행 결과:

x = 2, y = 1 복제!! x = 2, y = 1

 

  • 얕은 복사(Shallow Clone)와 깊은 복사 (Deep Clone)

내머내공 : 내 머리로 내가 공부했습니다

틀린 내용은 언제든지 알려주세요!!