Object对象详解(一)之clone

clone方法会返回该实例对象的一个副本,通常情况下x.clone() != x || x.clone().getClass() == x.getClass() || x.clone().equals(x)也为真,但不严格要求,我们可以通过重写该方法来覆盖。

protected native Object clone() throws CloneNotSupportedException;

可以看到,clone是一个本地方法,可能会抛出CloneNotSupportedException异常,什么情况下会抛出呢?

/**
 * A class implements the <code>Cloneable</code> interface to
 * indicate to the {@link java.lang.Object#clone()} method that it
 * is legal for that method to make a
 * field-for-field copy of instances of that class.
 * <p>
 * Invoking Object‘s clone method on an instance that does not implement the
 * <code>Cloneable</code> interface results in the exception
 * <code>CloneNotSupportedException</code> being thrown.
 * <p>
 * By convention, classes that implement this interface should override
 * <tt>Object.clone</tt> (which is protected) with a public method.
 * See {@link java.lang.Object#clone()} for details on overriding this
 * method.
 * <p>
 * Note that this interface does <i>not</i> contain the <tt>clone</tt> method.
 * Therefore, it is not possible to clone an object merely by virtue of the
 * fact that it implements this interface.  Even if the clone method is invoked
 * reflectively, there is no guarantee that it will succeed.
 *
 * @author  unascribed
 * @see     java.lang.CloneNotSupportedException
 * @see     java.lang.Object#clone()
 * @since   JDK1.0
 */
public interface Cloneable {
}

说明中写到,如果该对象未实现Cloneable 接口,那么当实例调用clone方法时,就会抛出该异常。

下面看Object中对于clone方法的描述。

    /**
     * Creates and returns a copy of this object.  The precise meaning
     * of "copy" may depend on the class of the object. The general
     * intent is that, for any object {@code x}, the expression:
     * <blockquote>
     * <pre>
     * x.clone() != x</pre></blockquote>
     * will be true, and that the expression:
     * <blockquote>
     * <pre>
     * x.clone().getClass() == x.getClass()</pre></blockquote>
     * will be {@code true}, but these are not absolute requirements.
     * While it is typically the case that:
     * <blockquote>
     * <pre>
     * x.clone().equals(x)</pre></blockquote>
     * will be {@code true}, this is not an absolute requirement.
     * <p>
     * By convention, the returned object should be obtained by calling
     * {@code super.clone}.  If a class and all of its superclasses (except
     * {@code Object}) obey this convention, it will be the case that
     * {@code x.clone().getClass() == x.getClass()}.
     * <p>
     * By convention, the object returned by this method should be independent
     * of this object (which is being cloned).  To achieve this independence,
     * it may be necessary to modify one or more fields of the object returned
     * by {@code super.clone} before returning it.  Typically, this means
     * copying any mutable objects that comprise the internal "deep structure"
     * of the object being cloned and replacing the references to these
     * objects with references to the copies.  If a class contains only
     * primitive fields or references to immutable objects, then it is usually
     * the case that no fields in the object returned by {@code super.clone}
     * need to be modified.
     * <p>
     * The method {@code clone} for class {@code Object} performs a
     * specific cloning operation. First, if the class of this object does
     * not implement the interface {@code Cloneable}, then a
     * {@code CloneNotSupportedException} is thrown. Note that all arrays
     * are considered to implement the interface {@code Cloneable} and that
     * the return type of the {@code clone} method of an array type {@code T[]}
     * is {@code T[]} where T is any reference or primitive type.
     * Otherwise, this method creates a new instance of the class of this
     * object and initializes all its fields with exactly the contents of
     * the corresponding fields of this object, as if by assignment; the
     * contents of the fields are not themselves cloned. Thus, this method
     * performs a "shallow copy" of this object, not a "deep copy" operation.
     * <p>
     * The class {@code Object} does not itself implement the interface
     * {@code Cloneable}, so calling the {@code clone} method on an object
     * whose class is {@code Object} will result in throwing an
     * exception at run time.
     *
     * @return     a clone of this instance.
     * @exception  CloneNotSupportedException  if the object‘s class does not
     *               support the {@code Cloneable} interface. Subclasses
     *               that override the {@code clone} method can also
     *               throw this exception to indicate that an instance cannot
     *               be cloned.
     * @see java.lang.Cloneable
     */
    protected native Object clone() throws CloneNotSupportedException;

其中提到的重写clone方法的几个注意点

1. 数组视为自动实现了Cloneable接口;

2. 非数组类型,使用clone方法,需要实现Cloneable接口,否则会抛出异常;

3. 非数组类型,克隆时,会新创建一个该类型的实例,并将被克隆对象实例的状态复制给新创建对象,并且这是一个浅克隆-(影子克隆——shallow copy),而不是deep copy;

4. 重写clone方法时,首先首先首先需要调用父类的clone方法。

那么问题来了,什么是shallow copy?而deep copy又是什么?

上例子:

public class Test {
    public static void main(String[] args) throws CloneNotSupportedException {
          People people = new People("zjh", ‘男‘, 21, new Cloth(COLOR.WHITE  , "XXL"));
          People clone = (People) people.clone();

          System.out.println("people == clone : " + (people == clone));
          System.out.println("people.getCloth() == clone.getCloth() : "+ (people.getCloth() == clone.getCloth()));

          System.out.println("people.getAge() == clone.getAge() : "+(people.getAge() == clone.getAge()));

          System.out.println("people.getName() == clone.getName() : "+(people.getName() == clone.getName()));
    }
}
class People implements Cloneable{
    private String name;
    private char sex;
    private int age;
    private Cloth cloth;

    /**
     * {@inheritDoc}.
     */
    @Override
    protected Object clone() throws CloneNotSupportedException {
        // TODO Auto-generated method stub
        return super.clone();
    }
    ...若干getter/setter方法
  }
class Cloth{
    private COLOR color;
    private String size;
    /**
     * 构造函数.
     *
     * @param color
     * @param size
     */
    public Cloth(COLOR color, String size) {
        super();
        this.color = color;
        this.size = size;
    }
    enum COLOR {
        RED,WHITE,BLACK,GREEN,BLUE
    }
}

运行结果:

people == clone : false

people.getCloth() == clone.getCloth() : true

people.getSex() == clone.getSex() : true

people.getName() == clone.getName() : true

age,sex,name比较为真还能理解,为什么people.getCloth() == clone.getCloth() 也是true呢?又做了下面的测试。

 people.getCloth().setColor(COLOR.BLACK);
          System.out.println(clone.getCloth().getColor());

运行结果:

BLACK

现在已经能确定,people和它的克隆对象clone中的cloth引用指向了同一个Cloth实例。这就是“shallow copy”。那么想要“deep copy”,那么就需要在重写方法的时候,同时调用对象属性的克隆方法(要求该属性对象也需要实现Cloneable)。

clone方法修改如下:

    protected Object clone() throws CloneNotSupportedException {
        // TODO Auto-generated method stub
        People clone =    (People) super.clone();
        clone.setCloth((Cloth)cloth.clone());
        return clone;
    }

再运行上面的测试程序:

people == clone : false

people.getCloth() == clone.getCloth() : false

people.getAge() == clone.getAge() : true

people.getSex() == clone.getSex() : true

people.getName() == clone.getName() : true

版权声明:本文为博主原创文章,未经博主允许不得转载。

时间: 2024-10-28 04:46:53

Object对象详解(一)之clone的相关文章

Object对象详解(一)之toString

Object作为Java中超然的存在,其中定义了一切对象都共有的方法. 特点: 1. java.lang包在使用的时候无需显示导入,编译时由编译器自动导入. 2. Object类是类层次结构的根,Java中所有的类从根本上都继承自这个类. 3. Object类是Java中唯一没有父类的类.其他所有的类,包括标准容器类,比如数组,都继承了Object类中的方法. 下面将详细介绍Object对象的一些方法. toString方法可以返回一个字符串类型的关于该类的描述信息,我们通常会重写为我们需要的该

Object对象详解(三)之hashCode与equals

从学习Java开始,就从各个师兄.各种书籍.各大网站听到.看到,重写equals方法必须重写hashCode方法.重写equals方法必须重写hashCode方法.重写equals方法必须重写hashCode方法. 那么为什么呢?今天就详细剖析一下equals和hashCode! equals方法是比较两个对象实例是否相等.Object中equals方法的描述为: public boolean equals(Object obj) { return (this == obj); } 也就是默认情

【转载】html中object标签详解

[转载自http://blog.csdn.net/soliy/archive/2010/03/22/5404183.aspx] html标签之Object标签详解 作者:网络    出处:网络    2010年3月22日13:36:29 定义和用法定义一个嵌入的对象.请使用此元素向您的 XHTML 页面添加多媒体.此元素允许您规定插入 HTML 文档中的对象的数据和参数,以及可用来显示和操作数据的代码.<object> 标签用于包含对象,比如图像.音频.视频.Java applets.Acti

JavaWeb学习(三)----JSP内置对象详解

[声明] 欢迎转载,但请保留文章原始出处→_→ 生命壹号:http://www.cnblogs.com/smyhvae/ 文章来源:http://www.cnblogs.com/smyhvae/p/4065790.html 联系方式:[email protected] [系列]JSP学习系列文章:(持续更新) JavaWeb学习(一)----JSP简介及入门(含Tomcat的使用) JavaWeb学习(二)----JSP脚本元素.指令元素.动作元素 JavaWeb学习(三)----JSP内置对象

JavaScript学习总结(十一)——Object类详解

一.Object类介绍 Object类是所有JavaScript类的基类(父类),提供了一种创建自定义对象的简单方式,不再需要程序员定义构造函数. 二.Object类主要属性 1.constructor:对象的构造函数. 2.prototype:获得类的prototype对象,static性质. 三.Object类主要方法 1.hasOwnProperty(propertyName) 判断对象是否有某个特定的属性.必须用字符串指定该属性,例如,obj.hasOwnProperty("name&q

【好文收藏】javascript中event对象详解

event代表事件的状态,例如触发event对象的元素.鼠标的位置及状态.按下的键等等. event对象只在事件发生的过程中才有效. event的某些属性只对特定的事件有意义.比如,fromElement 和 toElement 属性只对 onmouseover 和 onmouseout 事件有意义. 例子 下面的例子检查鼠标是否在链接上单击,并且,如果shift键被按下,就取消链接的跳转. <HTML> <HEAD><TITLE>Cancels Links</T

java对象详解

java对象详解 内存布局 普通对象布局 数组的内存布局 内部类的内存布局 对象分解 对象头-mark word(8字节) 实例数据 对齐填充(可选) java锁分析 java对象详解 HotSpot虚拟机中,对象在内存中存储的布局可以分为对象头,实例数据,对齐填充三个区域.本文所说环境均为HotSpot虚拟机.即输入java -version返回的虚拟机版本: java version "1.8.0_111" Java(TM) SE Runtime Environment (buil

javascript中event对象详解

event代表事件的状态,例如触发event对象的元素.鼠标的位置及状态.按下的键等等. event对象只在事件发生的过程中才有效. event的某些属性只对特定的事件有意义.比如,fromElement 和 toElement 属性只对 onmouseover 和 onmouseout 事件有意义. 例子 下面的例子检查鼠标是否在链接上单击,并且,如果shift键被按下,就取消链接的跳转. 前端UI资源I分享 <HTML> <HEAD><TITLE>Cancels L

JavaScript 对象详解

1 创建对象的方法 最常见的创建对象方法是通过new调用构造函数,此外还有一个方法就是使用Object.create(),将一个原型对象作为参数传递给Object.create也可以创建一个继承了其属性的新对象.但是和使用new创建对象还有一点差别,那就是构造函数不会被调用.所以如果使用这种方法创建一个foo新对象,其foo.f是undefined的: function Foo(z) { this.f = z; } Foo.prototype.add = function(x, y) { ret