標籤:
1.person類
1 //clone方法必須實現Cloneable介面 2 public class Person implements Cloneable { 3 private String name; 4 private int age; 5 public Calendar calendar; 6 7 public Person() { 8 } 9 10 // 構造方法11 public Person(String name, int age, Calendar calendar) {12 this.name = name;13 this.age = age;14 this.calendar = calendar;15 }16 17 @Override18 public Person clone() throws CloneNotSupportedException {19 Person cloned = (Person) super.clone();// 淺層複製20 cloned.calendar = (Calendar) calendar.clone();// 深度複製,複製屬性21 return cloned;22 }23 24 @Override25 public String toString() {// 重寫toString方法26 return "Person [ name = " + name + " | age = " + age + " | Calendar = " + calendar.getTime() + " ]";27 }28 29 public Calendar getCalendar() {30 return calendar;31 }32 33 public void setCalendar(Calendar calendar) {34 this.calendar = calendar;35 }36 37 public String getName() {38 return name;39 }40 41 public void setName(String name) {42 this.name = name;43 }44 45 public int getAge() {46 return age;47 }48 49 public void setAge(int age) {50 this.age = age;51 }52 53 }
2.複製測試
1 //複製測試 2 public class CloneTest00 { 3 public static void main(String[] args) throws CloneNotSupportedException { 4 Calendar now = Calendar.getInstance(); 5 Person p1 = new Person("Tim", 18, now); 6 Person p2 = p1.clone(); 7 p2.setName("danny"); 8 p2.setAge(11); 9 p2.calendar.set(2000, 11, 11);10 System.out.println("p2 = " + p2.toString());11 System.out.println("p1 = " + p1.toString());12 }13 }// 改變p2的值,不會改變p1的值
3.非複製測試
1 //非複製測試 2 public class NotCloneTest00 { 3 public static void main(String[] args) { 4 Calendar now = Calendar.getInstance(); 5 Person p1 = new Person("Tim", 18, now); 6 Person p2 = p1; 7 p2.setName("danny"); 8 p2.setAge(11); 9 p2.calendar.set(2000, 11, 11);10 System.out.println("p2 = " + p2.toString());11 System.out.println("p1 = " + p1.toString());12 }13 }// 改變p2的值,p1的值跟隨改變
java複製測試