4

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.

2 Answers2

2

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.

Community
  • 1
  • 1
Péter Török
  • 114,404
  • 31
  • 268
  • 329
  • If you're calling _super.clone_ in every _clone_ implementation, then you'll eventually call _Object#clone_. And that method will make shallow copy of all data fields. I think, OP has got it right. – Nikita Rybak Oct 21 '10 at 10:52
  • @Nikita, the first version of my answer was incorrect indeed, but I have since updated it, now I believe it is right. – Péter Török Oct 21 '10 at 10:55
  • If any of `B`'s ancestors define `clone` in terms of a copy constructor rather than in terms of `Object`, then `B` must do likewise. If `B` uses a copy constructor even though all its ancestors chain to `base.clone`, it compels all of its descendents to likewise use a copy constructor. Personally, I find irksome the notion of clone methods that do anything other than chaining to `base.clone`, but such methods are alas very common. – supercat Jan 18 '12 at 19:25
0

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.

supercat
  • 77,689
  • 9
  • 166
  • 211