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
Creating a copy using the clone() method The class whose object's copy is to be made must have a public clone method in it or in one of its parent class. Every class that implements clone() should call super. clone() to obtain the cloned object reference. The class must also implement java.
clone() is a method in the Java programming language for object duplication. In Java, objects are manipulated through reference variables, and there is no operator for copying an object—the assignment operator duplicates the reference, not the object. The clone() method provides this missing functionality.
clone() doesn't call a constructor. You can only do this (unconditionally) if the class is final , because then you can guarantee to be returning an object of the same type as the original.
Yes, because the clone() method is protected it can be only inherited, but you can't call it on object of another class. Every class inherit Object, so you can just call clone().
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With