java複製測試

來源:互聯網
上載者:User

標籤:

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複製測試

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.