Java : clone() operation calling super.clone()

I am not fully understanding the idea of returning super.clone() in the clone() method of a class. First of all, wouldn't that relate to it returning an object that is a superclass which contains LESS data than requested, because a superclass "is not a" subclass, but a subclass "is a" superclass. And if there were a long chain of subclasses, each calling super.clone(), why wouldn't that lead to it eventually calling Object.clone() at the root of the chain, which isn't any of the subclasses?

Sorry if that was confusing; I confuse myself sometimes


Solution 1:

The implementation of clone() in Object checks if the actual class implements Cloneable, and creates an instance of that actual class.

So if you want to make your class cloneable, you have to implement Cloneable and downcast the result of super.clone() to your class. Another burden is that the call to super.clone() can throw a CloneNotSupportedException that you have to catch, even though you know it won't happen (since your class implements Cloneable).

The Cloneable interface and the clone method on the Object class are an obvious case of object-oriented design gone wrong.

Solution 2:

Consider this: you have a chain of inheriting classes. each may (or may not) have its own variables. what clone does, as opposed to the equals operator (==) that duplicates the reference, is a cloned copy of the object with a new reference. For the example above, you would like to clone the last object in the chain. As the last object is constructed of its superclasses, where each may have a different cloning method implementation, it makes a lot of sense to call the superclass implementation of clone to receive first a cloned parent object before cloning own object.

Another terms that are usually associated with cloning is shallow and deep cloning. shallow cloning refer to the creation of an exact replica of an object, while deep cloning creates a replica of an object and any child object that the original object refers to.

More on cloning at this link

Solution 3:

Read the javadoc of Object.clone() more carefully : it returns a copy of the object. The copy is another instance of the same class as that of the object on which clone is invoked. I.e. foo.clone().getClass() == foo.getClass().