I have a quick question regarding the clone() method in Java, used as super.clone() in regard to inheritance – where I call the clone() method in the parent class all the way up from the button.
The clone() method is supposed to return a copy of this object, however if I have three classes in an inheritance heirachy and call super.clone() three times, why doesn’t the highest class in the inheritance heirachy, just under class Object, get a copy of that class returned?
Suppose we have three classes: A, B and C, where A -> B -> C (inherit = ->)
Then calling super.clone() in class C, invokes clone() in B which calls super.clone(), invoke clone() in A which call super.clone() ‘this time Object.clone() gets called’. Why is it not a copy of the this object with respect to class A that gets returned from Object.clone()? That sounds logical to me.
It sounds like there are at least two problems at work here:
It sounds like you’re confused about how clone() normally gets implemented.
It sounds like you’re thinking that cloning is a good idea (vs. using a copy constructor, factories or their equivalent).
Here is an example of an implementation of a clone method:
Note that the result of
super.clone()is immediately cast to aFruit. That allows the inheriting method to then modify the Fruit-specific member data (fBestBeforeDatein this case).Thus, the call to a child
clone()method, while it will call the parents’ clones, also adds its own specific modifications to the newly made copy. What comes out, in this case, will be aFruit, not anObject.Now, more importantly, cloning is a bad idea. Copy constructors and factories provide much more intuitive and easily maintained alternatives. Try reading the header on the Java Practices link that I attached to the example: that summarizes some of the problems. Josh Bloch also has a much longer discussion: cloning should definitely be avoided. Here is an excellent summary paragraph on why he thinks cloning is a problem: