开发者

Does a subclass need to override the clone() method explicitly if the superclass has already done it?

开发者 https://www.devze.com 2023-01-21 20:49 出处:网络
If class A extends class B and class B has already implemented the Cloneable interface, then is it necessary for class A to declare \'clone() throws CloneNotSupportedException开发者_运维知识库\'?

If class A extends class B and class B has already implemented the Cloneable interface, then is it necessary for class A to declare 'clone() throws CloneNotSupportedException开发者_运维知识库'?

I guess it should not be mandatory, as the property to clone objects of class A would automatically be inherited from class B.


It is necessary to override clone() if class B defines non-primitve mutable member fields. These need to be deep copied explicitly within B.clone(). If B only contains primitive and/or immutable data members, A.clone() will do the job.

For a more detailed explanation, see this earlier answer of mine to a similar question.


If the parent class, and all ancestors, implements its Clone method by calling its parent class' Clone method, all the way up to Object.clone, and if none of the fields added by the subclass hold references to things which should be changeable on one object without affecting the other, then one can simply inherit clone without overriding it. If the parent class implements the clone method as described above but the subclass adds fields that themselves need to be cloned, the best pattern is for the subclass to call base.Clone and then clone the appropriate fields.

If the parent class or any ancestor does not implement its Clone method as described above but instead uses a copy constructor, then the derived class, and all base classes derived from it) must override Clone to do likewise, regardless of whether the base class adds any new fields.

Unfortunately, I know of no nice way to ascertain which category a parent class belongs to. If a parent class supports Clone by calling base.Clone, it would be unfortunate for a derived class to needlessly break the chain by implementing a copy constructor. On the other hand, if the parent class implements Clone as a copy constructor, a base class which does not do so will have broken semantics.

0

精彩评论

暂无评论...
验证码 换一张
取 消