实现深克隆

关键点:

1. 要实现Cloneable 哪怕他是一个空接口

2. 自己定义一个克隆用的方法 且在方法内部 调用 super.clone()

示例代码:

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
public class test11 {  
public static void main(String[] args) {
Sheep s1 = new Sheep(1, "小羊");
Sheep s2 = s1.clone();
s2.age = 2;
s2.name = "大羊";
s1.speak();
s2.speak();
}
}

class Sheep implements Cloneable {
int age;
String name;

public Sheep(int age, String name) {
this.age = age;
this.name = name;
}

void speak() {
System.out.println("我叫" + name + ",今年" + age + "岁了");
}

public Sheep clone() {
try {
return (Sheep) super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
throw new RuntimeException();
}
}
}