clone()方法

package com.yyr.clone;

//why clone? A与B是两个独立对象,但B的初始值由A对象确定的。so,clone()方法是最简单也是最高效的手段。
public class CloneTest {
public static void main(String[] args) throws CloneNotSupportedException {
    Face face=new Face("yyr",18);
    Face face1=(Face) face.clone();
    Face face2=face;
    System.out.println(face1==face);//false 对象复制(克隆) 地址是不相同的 创建新的对象
    System.out.println(face2==face);//true  引用的复制  地址仍然是相同的 是指向同一个对象
    //注意:clone方法执行的是浅拷贝
    String result=face.getName()==face1.getName()?"clone是浅拷贝":"clone是深拷贝";
    System.out.println(result);//clone是浅拷贝
    
    /** 深克隆
     * 1.拷贝对象实现Cloneable接口,实现clone()方法【Body类】
     * 2.在clone方法内部,把该对象引用的其他对象也要clone一份【Body类 clone()方法】
     * 3.被引用的对象也要实现Cloneable接口,实现clone()方法【Head类】
     */

    Body body=new Body(new Head(new Face()));
    Body body1=(Body) body.clone();
    System.out.println("body==body1:"+(body==body1));//false
    System.out.println("body.head==body1.head:"+(body.head==body1.head));//false
}

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{
    private String name;
    private int age;
    
    public Face() {
        super();
    }
    public Face(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    @Override
    public String toString() {
        return "Face [name=" + name + ", age=" + age + "]";
    }
    @Override
    protected Object clone() throws CloneNotSupportedException {
        return (Face)super.clone();
    }
    
}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值