본문 바로가기

Dev. Java/Java.lang

데이터 복제 clone() 메소드

// Cloneable 인터페이스를 구현한 클래스의 인스턴스만 clone()을 통한 복제가 가능함

class Point implements Cloneable{

int x;

int y;

Point(int x, int y){

this.x = x;

this.y = y;

}

@Override

public String toString() {

return "Point [x=" + x + ", y=" + y + "]";

}

public Object clone(){

Object obj = null;

try{

obj = super.clone();

}catch(CloneNotSupportedException e) {}

return obj;

}

}


public class CloneEx1 {

public static void main(String args[]){

Point origin = new Point(3, 5);

Point copy = (Point) origin.clone();  // 복제해서 새로운 객체를 생성

System.out.println(origin);

System.out.println(copy);

}

}