본문 바로가기

자바 기초

자바 clone() 메서드 - Do it ! 자바프로그래밍기초

clone() 메서드는 객체 원본을 유지해 놓고 복사본을 사용한다거나, 기본 틀의 복사본을 사용해 동일한 인스턴스를 만들어 복잡한 생성 과정을 간단히 하려는 경우에 사용한다.

 

protected Object clone();

 

clone() 메서드는 위와 같이 Object 클래스에 선언되어 있으며 객체를 복사해 또 다른 객체를 반환해준다.

 

package object;

class Point {
	int x;
	int y;
	
	Point(int x, int y) {
		this.x = x;
		this.y = y;
	}
	
	public String toString() {
		return "x = " + x + ", y = " + y;
	}
}

class Circle implements Cloneable { // 객체를 복제해도 된다는 의미로 Cloneable 인터페이스 함께 선언
	Point point;
	int radius;
	
	Circle(int x, int y, int radius) {
		this.radius = radius;
		point = new Point(x,y);
	}
	
	public String toString() {
		return "원점은 " + point + "이고, 반지름은 " + radius +"입니다.";
	}
	
	@Override             // clone() 메서드를 사용할 때 발생할 수 있는 오류를 예외처리함
	public Object clone() throws CloneNotSupportedException {
		return super.clone();
	}
}

public class ObjectCloneTest {

	public static void main(String[] args) throws CloneNotSupportedException {
		Circle circle = new Circle(10,20,30);
		Circle copyCircle = (Circle)circle.clone();
		
		System.out.println(circle);
		System.out.println(copyCircle);
		System.out.println(System.identityHashCode(circle));
		System.out.println(System.identityHashCode(copyCircle));
		
	}

}

 

clone() 메서드를 사용하려면 객체를 복제해도 된다는 의미로 Cloneable 인터페이스를 구현해야한다.

circle 인스턴스와 copyCircle 인스턴스의 해시코드가 서로 다른 값을 출력했는데, 

Object의 clone() 메서드는 클래스의 인스턴스를 새로 복제하여 생성해주기 때문이다. 

즉 멤버변수가 동일한 인스턴스가 다른 메모리에 새로 생성된다는 것이다.