代码:
package deepcopy;
public class DeepCopy {
static class Body implements Cloneable {
public Head head;
public Body() {
}
public Body(Head head) {
this.head = head;
}
//重写 clone 方法
@Override
protected Object clone() throws CloneNotSupportedException {
Body newBody = (Body) super.clone();
newBody.head = (Head) head.clone();
return newBody;
}
}
static class Head implements Cloneable {
public Face faces;
public Head() {
}
public Head(Face face) {
this.faces = face;
}
//重写 clone 方法
@Override
protected Object clone() throws CloneNotSupportedException {
Head head = (Head) super.clone();
head.faces = (Face)this.faces.clone();
return head;
}
}
static class Face implements Cloneable{
//重写 clone 方法
@Override
protected Object clone() throws CloneNotSupportedException{
return super.clone();
}
}
public static void main(String[] args) throws CloneNotSupportedException {
Body body = new Body(new Head());
Body body1 = (Body) body.clone();
System.out.println(body == body1);
System.out.println(body.head == body1.head);
System.out.println(body.head.faces == body1.head.faces);
System.out.println(body.head);
System.out.println(body1.head);
}
}
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.