-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDeepCopyForCloneable.java
More file actions
61 lines (50 loc) · 1.27 KB
/
DeepCopyForCloneable.java
File metadata and controls
61 lines (50 loc) · 1.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package com.cloneable;
/**
* 深度copy
* @author ken
*/
class StudentD2 implements Cloneable {
String name;
int age;
StudentD2(String name, int age) {
this.name = name;
this.age = age;
}
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
class TeacherD2 implements Cloneable {
String name;
int age;
StudentD2 student;
TeacherD2(String name, int age, StudentD2 student) {
this.name = name;
this.age = age;
this.student = student;
}
public Object clone() throws CloneNotSupportedException {
TeacherD2 teacher = (TeacherD2) super.clone();
teacher.student = (StudentD2) student.clone();
return teacher;
}
}
public class DeepCopyForCloneable {
public static void main(String[] args) {
StudentD2 student = new StudentD2("小明", 10);
TeacherD2 t = new TeacherD2("张老师", 30, student);
try {
TeacherD2 t2 = (TeacherD2) t.clone();
t2.student.age = 21;
t2.student.name = "test";
t2.age = 32;
t2.name = "李老师";
System.out.println("学生名称:" + t.student.name + ",年龄" + t.student.age);
} catch (Exception e) {
e.printStackTrace();
for (StackTraceElement ele : e.getStackTrace()) {
System.out.println(ele);
}
}
}
}