现在为了要在clone对象时进行深复制, 那么就要Clonable接口,覆盖并实现clone方法,除了调用父类中的clone方法得到新的对象, 还要将该类中的引用变量也clone出来。
代码语言:javascript复制public class Test {
static class Body implements Cloneable {
public Head head;
public Body() {
}
public Body(Head head) {
this.head = head;
}
@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 face;
public Head() {
}
public Head(Face face) {
this.face = face;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
static class Face implements Cloneable {
public Face() {
}
}
public static void main(String[] args) throws CloneNotSupportedException {
Body body = new Body(new Head());
Body body1 = (Body) body.clone();
System.out.println("body == body1 : " (body == body1));
System.out.println("body.head == body1.head : " (body.head == body1.head));
}
}
打印结果为:
代码语言:javascript复制body == body1 : false
body.head == body1.head : false
由此可见, body和body1内的head引用指向了不同的Head对象, 也就是说在clone Body对象的同时, 也复制了它所引用的Head对象, 进行了深复制。但实际上上面代码还不是真正意义上的深复制,可以说是不彻底的深复制。因为在拷贝Head类时,默认执行的是浅复制,也就是说Head中组合的Face对象并不会被复制。