Java

Java 문법 ) Object클래스 - clone

sejin2 2023. 11. 2. 14:25

Object 클래스 메서드 중

protected Object 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 "x = " + x + ", y = " + y;
	} 
	public Object clone() {
		Object obj = null;
		
		try {
			obj = super.clone();	// 그냥 clone 하면 내꺼 호출, 지금은 부모꺼 호출
		} catch (CloneNotSupportedException e) { 
			e.printStackTrace();
		}
		return obj;	// 복제한 것 return 
	}
}

public class Clone04 {

	public static void main(String[] args) {
		Point originP = new Point(3, 5);
		Point copy = (Point)originP.clone();	// 자식타입으로 만든 것을 부모타입으로 변경될 것을 다시 자식타입(Point)으로 변환
		
		System.out.println(originP);  // x = 3, y = 5 출력
		System.out.println(copy);  // x = 3, y = 5 출력
		
		System.out.println(originP.hashCode());  // 1651191114 출력
		System.out.println(copy.hashCode());  // 1586600255 출력
		
		int[] arr = {1, 2, 3, 4, 5};
		int[] arrClone = arr.clone();
		System.arraycopy(arr, 0, arrClone, 0, arr.length); 
		
		System.out.println(arrClone[0]); // 1 출력
		System.out.println("-------");
		
		arrClone[0] = 9;
		System.out.println(arr[0]);  // 1 출력
		System.out.println(arrClone[0]);   // 9 출력
	} 
}