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 @Override 18 public Person clone() throws CloneNotSupportedException { 19 Person cloned = (Person) super.clone();// 浅层克隆 20 cloned.calendar = (Calendar) calendar.clone();// 深度克隆,克隆属性 21 return cloned; 22 } 23 24 @Override 25 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的值跟随改变
时间: 2024-10-11 04:48:57