Cloneable接口(java,clone接口的使用)

1、通识性问题说明:

(1)String类不可被clone(String不可修改)

(2)Clone对应的异常:CloneNotSupportedException

2、克隆的自定义实现 : 实现Cloneable接口的类需要重写clone方法


public class CloneTest {
    public static void main(String[] args) {
        Circle circle = new Circle();
        Circle circle2 = (Circle) circle.clone();
        System.out.println(circle);
        System.out.println(circle2);
    }
}
/*自定义实现clone*/
class Circle implements Cloneable{
    private double radius = 1.0;
    public final double PI = 3.14;

    @Override
    protected Object clone() throws CloneNotSupportedException {
        try {
            return super.clone();
        }catch (CloneNotSupportedException e){
            return null;
        }
    }
}

运行后发现,通过克隆得到了新的Circle对象

 

3、浅拷贝:

public class TVTest {
    public static void main(String[] args) throws CloneNotSupportedException {
        TV a = new TV();
        TV b = (TV) a.clone();
    }
}

class TV implements Cloneable{
    private boolean on;
    private Date buyDate = new Date();

    @Override
    protected Object clone() throws CloneNotSupportedException {
        try {
            return super.clone();
        }catch (CloneNotSupportedException e){
            return null;
        }
    }
}

4、深拷贝:

import java.util.Date;

public class TVTest {
    public static void main(String[] args) throws CloneNotSupportedException {
        TV a = new TV();
        TV b = (TV) a.clone();
    }
}

class TV implements Cloneable{
    private boolean on;
    private Date buyDate = new Date();

    @Override
    protected Object clone() throws CloneNotSupportedException {
        try {
            TV temTV = (TV) super.clone();
            temTV.buyDate = (Date) buyDate .clone();
            return temTV;
        }catch (CloneNotSupportedException e){
            return null;
        }
    }
}

 

 写代码时最好是用深拷贝,因为这样不至于在改了一个公共引用对象后,产生数据矛盾,把不该改的地方也改了。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值