class Employee implements Cloneable
{
public Employee clone() throws CloneSupportedException
{
return (Employee)super.clone();
}
}
/**
* This (empty) interface must be implemented by all classes that wish to
* support cloning. The implementation of {@code clone()} in {@code Object}
* checks if the object being cloned implements this interface and throws
* {@code CloneNotSupportedException} if it does not.
*
* @see Object#clone
* @see CloneNotSupportedException
* @since Android 1.0
*/
public interface Cloneable {
// Marker interface
}
/*
…………
* @return a clone of this instance.
* @exception? CloneNotSupportedException? if the object's class does not
*support the Cloneable interface. Subclasses
*that override the 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;
1.为什么调用super.clone()方法能否经过转换后就能生成一个Employee的副本,它不是生成一个object的副本吗?
答:Object中的clone执行的时候使用了RTTI(run-time type identification)的机制,动态得找到目前正在调用clone方法的那个reference,根据它的大小申请内存空间,然后进行bitwise的复制,将该对象的内存空间完全复制到新的空间中去,从而达到shallowcopy【浅copy】的目的。 所以你调用super.clone() 得到的是当前调用类的副本,而不是父类的副本。
2.为什么要实现Cloneable接口?
指示Object.clone() 方法可以合法地对该类实例进行按字段复制
首先,Cloneable 这个接口仅做标识用,用于告诉调用者,“这个 class 是 cloneable 的”。
不过,如果你的 class 仅仅实现了这个接口,那是不够的。根据 JDK 文档,实现这个接口的同时,还要重写 clone() 方法。直接的理由很简单,如果不重写的话,Object.clone() 是 protected 的,不能被外部调用,重写时要改成 public 才可以。
至于“为什么要这样设计”,我想,可能是因为,实际使用 clone() 的场合大多数都需要的是“deep copy”,而 Object.clone() 实现的只是一个 field-to-field 的“shallow copy”,所以,要自己实现 clone() 方法对 Object reference 型的成员再进行 clone()。
再进一步,至于为什么 Object.clone() 不直接实现成“deep copy”,我想,可能是因为那样就太过分了,实际使用时并不一定都是完全的 deep copy,也许有些成员只要 shallow copy 就够了。所以,还是把具体实现的方法交给程序员决定。
原型构造函数
http://blog.youkuaiyun.com/kenthong/article/details/5758884
http://www.iteye.com/topic/483469
本文详细解析了Java中Cloneable接口与Object类clone方法的使用,解释了为何调用super.clone()能得到当前类的副本,以及实现Cloneable接口的重要性。通过实例代码,深入探讨了clone方法的实现细节与保护权限机制。
495

被折叠的 条评论
为什么被折叠?



