Does subclass need to override Clone() method explicitly if superclass has already done it

老子叫甜甜 提交于 2020-01-16 05:09:12

问题


If Class A extends class B and class B has already implemented cloneable interface then is it necessary for class A to declare 'clone() throws CloneNotSupportedException' .

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


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/3986588/does-subclass-need-to-override-clone-method-explicitly-if-superclass-has-alrea

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!