代码:
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);
}
}
1
lwlizhe 2020-11-16 19:27:19 +08:00
额,不知道是不是全部代码……
不过我感觉这种空指针应该是最简单的错误了哈……这种问题自己看下报错信息……我感觉这种问题没多大意义…… 回正题 乍看应该是 head 中 face 为空导致的,跟拷不拷贝好像没什么关系,body.clone 调用了 head.clone,head.clone 调用了 face.clone,然而 face 是空的 |