码迷,mamicode.com
首页 > 编程语言 > 详细

关于Java clone(浅克隆) 的代码

时间:2017-07-28 21:02:19      阅读:228      评论:0      收藏:0      [点我收藏+]

标签: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     @Override
43     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]
false
true
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=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]
false
true
Student [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(浅克隆) 的代码

标签:public   util   object   date()   color   ring   克隆   exce   str   

原文地址:http://www.cnblogs.com/zuosy/p/7252348.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!