關於Java clone(淺複製) 的代碼

來源:互聯網
上載者:User

標籤:public   util   object   date()   color   ring   複製   exce   str   

 1 import java.util.Date; 2  3 public class HelloWorld{ 4     public static void main(String[] args) throws CloneNotSupportedException{ 5         Student stu1 = new Student(); 6         Student stu2 = (Student)stu1.clone(stu1); 7          8         System.out.println(stu1); 9         System.out.println(stu2);10         System.out.println(stu1 == stu2);11         System.out.println(stu1.createDate == stu2.createDate);12         13         stu2.createDate = new Date();14         stu2.name = "TomCat";15         stu2.age = 2333;16         17         System.out.println(stu1);18         System.out.println(stu2);19         20         System.out.println(stu1.createDate == stu2.createDate);21         22     }23 }24 class Student implements Cloneable {25     public Date createDate = new Date();26     public String name;27     public int age;28     29     public Student() {30         this("Stupid", 18);31     }32     33     public Student(String name, int age) {34         this.name = name;35         this.age = age;36     }37     38     public Object clone(Object o) throws CloneNotSupportedException {39         return super.clone();40     }41 42     @Override43     public String toString() {44         return "Student [createDate=" + createDate + ", name=" + name + ", age=" + age + "]";45     }46 }
Student [createDate=Fri Jul 28 19:46:06 CST 2017, name=Stupid, age=18]Student [createDate=Fri Jul 28 19:46:06 CST 2017, name=Stupid, age=18]falsetrueStudent [createDate=Fri Jul 28 19:46:06 CST 2017, name=Stupid, age=18]Student [createDate=Fri Jul 28 19:46:06 CST 2017, name=TomCat, age=2333]false

new Date(); 是有建立了一個對象 其引用是是stu2.createDate 

QAQ 我錯了,我錯了,我錯了,我錯了

應該寫成下面樣子

1 stu2.createDate.setYear(1900);
Student [createDate=Fri Jul 28 19:51:05 CST 2017, name=Stupid, age=18]Student [createDate=Fri Jul 28 19:51:05 CST 2017, name=Stupid, age=18]falsetrueStudent [createDate=Mon Jul 28 19:51:05 CST 3800, name=Stupid, age=18]Student [createDate=Mon Jul 28 19:51:05 CST 3800, name=TomCat, age=2333]true

所以clone方法是一個淺複製

QAQ

關於Java clone(淺複製) 的代碼

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.