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
加一个图片解释一下