package edu.exam11.ex01clone;
//얕은복사
class Point{
	private int x;
	private int y;
	
	Point(int x, int y){
		this.x = x;
		this.y = y;
		
	}
	void setPoint(int x, int y) {
		this.x = x;
		this.y = y;
		
	}	
	void showPoint() {
		System.out.printf("[%d. %d]\n", x,y);
		
	}	
}
//객체자체가 복제되지 않고
//가리키는 참조값만 복사되므로
//같은 객체를 2개의 변수가 가리키게 된다.
public class PointClone {
	public static void main(String[] args) {
		Point org = new Point(10, 20);
		Point cpy = org;	// 얕은 복사   참조값이 복사됨
		System.out.println(org);
		System.out.println(cpy);
		org.showPoint();
		cpy.showPoint();
		cpy.setPoint(100, 200);
		org.showPoint();
	}
}
package edu.exam11.ex02clone;
//깊은복사
//클래스의 객체를 복제(새롭게 생성해서 값을 복사)하고 싶으면 
//Cloneable 인터페이스를 상속받아라
class Point implements Cloneable{
	@Override
	public Object clone() throws CloneNotSupportedException {
		// TODO Auto-generated method stub
		return super.clone();
	}
	private int x;
	private int y;
	
	Point(int x, int y){
		this.x = x;
		this.y = y;
		
	}
	void setPoint(int x, int y) {
		this.x = x;
		this.y = y;		
	}
	
	void showPoint() {
		System.out.printf("[%d. %d]\n", x,y);		
	}	
}
public class PointClone {
	public static void main(String[] args) {
		Point org = new Point(10, 20);
		Point cpy;
		try {
			cpy = (Point)org.clone();	// 깊은 복사
			
			System.out.println(org);
			System.out.println(cpy);
			org.showPoint();
			cpy.showPoint();
			cpy.setPoint(100, 200);
			org.showPoint();
	
		} catch (CloneNotSupportedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}			
	}
}

'JAVA > java 예제' 카테고리의 다른 글

TreeSet 예제  (0) 2020.01.29
TreeSet 정렬 예제  (0) 2020.01.29
링크드리스트 구현 예제  (0) 2020.01.20
링크드리스트로 구현한 주소록 프로그램  (0) 2020.01.20
선형 배열 리스트 예제  (0) 2020.01.16

+ Recent posts