代码:
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);
}
}