Skip to content

Commit c17181e

Browse files
author
huiwenlong
committed
修复浅拷贝和深拷贝
1 parent 62834be commit c17181e

File tree

1 file changed

+34
-13
lines changed

1 file changed

+34
-13
lines changed

src/org/javacore/base/copy/CopyT.java

+34-13
Original file line numberDiff line numberDiff line change
@@ -32,10 +32,20 @@ public void setName(String name) {
3232
this.name = name;
3333
}
3434

35-
@Override
36-
protected Object clone() throws CloneNotSupportedException {
37-
return super.clone();
38-
}
35+
/**
36+
* 深拷贝
37+
* @return
38+
*/
39+
/*@Override
40+
public Object clone() {
41+
Object o = null;
42+
try {
43+
o = super.clone();
44+
} catch (CloneNotSupportedException e) {
45+
e.printStackTrace();
46+
}
47+
return o;
48+
}*/
3949
}
4050
class Student implements Cloneable{
4151
private String name;
@@ -57,10 +67,30 @@ public void setFamily(Family family) {
5767
this.family = family;
5868
}
5969

70+
/**
71+
* 浅拷贝 对其对象的引用却没有拷贝
72+
* @return
73+
* @throws CloneNotSupportedException
74+
*/
6075
@Override
6176
protected Object clone() throws CloneNotSupportedException {
6277
return super.clone();
6378
}
79+
80+
/**
81+
* 深拷贝
82+
*/
83+
/*@Override
84+
protected Object clone() {
85+
Student o = null;
86+
try {
87+
o = (Student)super.clone();
88+
} catch (CloneNotSupportedException e) {
89+
e.printStackTrace();
90+
}
91+
o.family = (Family) family.clone();
92+
return o;
93+
}*/
6494
}
6595

6696
public class CopyT {
@@ -71,19 +101,10 @@ public static void main(String[] args) throws CloneNotSupportedException {
71101
student1.setFamily(family);
72102
student1.setName("Jeff");
73103

74-
// 浅拷贝
75-
// 对其对象的引用却没有拷贝
76104
Student student2 = (Student) student1.clone();
77105
student2.setName("Jeff2");
78106
student2.getFamily().setName("Jeff2 Family");
79107
System.out.println(student1.getName() + " " + student1.getFamily().getName());
80108
System.out.println(student2.getName() + " " + student2.getFamily().getName());
81-
82-
// 深拷贝
83-
// Student student2 = (Student) student1.clone();
84-
// student2.setName("Jeff2");
85-
// student2.getFamily().setName("Jeff2 Family");
86-
// System.out.println(student1.getName() + " " + student1.getFamily().getName());
87-
// System.out.println(student2.getName() + " " + student2.getFamily().getName());
88109
}
89110
}

0 commit comments

Comments
 (0)