`
默翁1
  • 浏览: 25383 次
社区版块
存档分类
最新评论

clone深度复制

    博客分类:
  • java
 
阅读更多
package mianshi;

public 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();
        Head newHead = (Head) super.clone();
        newHead.face = (Face) this.face.clone();
        return newHead;
    }
}
 
static class Face implements Cloneable{
    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}
 
public static void main(String[] args) throws CloneNotSupportedException {
     
    Body body = new Body(new Head(new Face()));
     
    Body body1 = (Body) body.clone();
     
    System.out.println("body == body1 : " + (body == body1) );
     
    System.out.println("body.head == body1.head : " +  (body.head == body1.head));
     
    System.out.println("body.head.face == body1.head.face : " +  (body.head.face == body1.head.face));
     
     
}
}
 

 

body == body1 : false
body.head == body1.head : false
body.head.face == body1.head.face : false

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics