正确增加Cloneable接口

今天调试程序,发现在解析的时候使用了clone函数,但是得到的结果是null,很奇怪。

看代码,override了clone函数,还是得到null。

继续搜索stackoverflow,发现没有增加Cloneable接口声明。

增加声明后,问题解决。

http://stackoverflow.com/questions/1052340/what-is-wrong-with-this-clone

The standard pattern for making a class cloneable is:

  1. Implement Cloneable
  2. Override the clone() method and make it public
  3. In clone() call super.clone() and then copy any mutable object's state

You should not create a new object using new. The proper way is to call super.clone() for a new instance. Object's clone() is special and will create a new copy of the object and copy its primitive fields and references.

你不需要使用new关键字创建新对象。合适的方法是调用super.clone建立新对象。Object的clone()是特别的,会创建一个新的对象拷贝,以及拷贝它的基本类型和引用。(这里涉及到深拷贝和浅拷贝,请自行glgoo.com)

For example:

public class Person implements Cloneable {
    protected String name;
    // Note that overridden clone is public
    public Object clone() {
        Person clone = (Person)super.clone();
        // No need to copy name as the reference will be
        // copied by Object's clone and String is immutable
        return clone;
    }
}

public class Employee extends Person {
    protected int id;
    protected java.awt.Point location;
    public Object clone() {
        Employee  clone = (Employee )super.clone();
        // No need to copy id as Object's clone has already copied it
        // Need to clone location as Point is mutable and could change
        clone.location = location.clone();
        return clone;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值