1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
| class Person implements Cloneable{ String name; int age; int[] score; public Person(String name, int age, int[] score){ this.name = name; this.age = age; this.score = score; }
@Override public String toString() { return "person [name=" + name + ", age=" + age + ", score=" + Arrays.toString(score) + "]"; }
@Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } }
public class CustomCloneTest {
public static void main(String[] args) throws CloneNotSupportedException { Person or = new Person("홍길동", 20, new int[]{100,30}); Object cloned = or.clone(); System.out.println("원본과 복제품1 >> "+or+" : "+cloned); System.out.println("원본과 복제품1의 해쉬코드비교 >> "+System.identityHashCode(or) +" : "+System.identityHashCode(cloned)); or.age = 77; System.out.println("원본의 age변경 >> "+or+" : "+cloned); or.score[0] = 3; System.out.println("원본의 score변경 >> "+or+" : "+cloned); p1.name = "재재"; System.out.println("클론의 name변경 >> "+or+" : "+p1); Person p1 = (Person) cloned; p1.score[0] = 12; System.out.println("클론의 score변경 >> "+or+" : "+p1); }
}
원본과 복제품1 >> [name=홍길동, age=20, score=[100, 30]] : [name=홍길동, age=20, score=[100, 30]] 원본과 복제품1의 해쉬코드비교 >> 366712642 : 1829164700
원본의 age변경 >> [name=홍길동, age=77, score=[100, 30]] : [name=홍길동, age=20, score=[100, 30]] 원본의 score변경 >> [name=홍길동, age=77, score=[3, 30]] : [name=홍길동, age=20, score=[3, 30]] 클론의 name변경 >> [name=홍길동, age=77, score=[12, 30]] : [name=재재, age=20, score=[12, 30]] 클론의 score변경 >> [name=홍길동, age=77, score=[12, 30]] : [name=홍길동, age=20, score=[12, 30]]
|