48. 2 , Java 的 clone() 方法
Clone
protected Object clone() throws CloneNotSupportedException
This method may be called to create a new copy of the Object. The typical
behavior is as follows:
o == o.clone() is false
o.getClass() == o.clone().getClass() is true
o.equals(o) is true
However, these are not strict requirements, and may be violated if necessary. Of
the three requirements, the last is the most commonly violated, particularly if
the subclass does not override equals(Object) 55 .
If the Object you call clone() on does not implement Cloneable (which is a
placeholder interface), then a CloneNotSupportedException is thrown. Notice
that Object does not implement Cloneable; this method exists as a
convenience for subclasses that do.
Object's implementation of clone allocates space for the new Object using the
correct class, without calling any constructors, and then fills in all of the new
field values with the old field values. Thus, it is a shallow copy. However,
subclasses are permitted to make a deep copy.
All array types implement Cloneable, and override this method as follows (it
should never fail):
public Object clone() { try { super.clone(); } catch (CloneNotSupportedException
e) { throw new InternalError(e.getMessage()); } }
49. 2 , Java 的 clone() 方法
⑴clone 方法将对象复制了一份并返回给调用者。一
般而言, clone ()方法满足:
① 对任何的对象 x ,都有 x.clone() !=x
克隆对象与原对象不是同一个对象
② 对任何的对象 x ,都有
x.clone().getClass()==x.getClass()
克隆对象与原对象的类型一样
③ 如果对象 x 的 equals() 方法定义恰当,那么
x.clone().equals(x) 应该成立。
⑵Java 中对象的克隆
① 为了获取对象的一份拷贝,我们可以利用 Object 类的
clone() 方法。
② 在派生类中覆盖基类的 clone() 方法,并声明为
public 。
③ 在派生类的 clone() 方法中,调用 super.clone() 。