If I have:
class foo implements Cloneable
and then do:
bar = new foo();
bar.clone();
I get a shallow copy without needing to write any bar.clone()
code like I normally would need to do when I implement an interface.
My understanding is that an interface's functions must be filled in by the class implementing it, and Object.clone()
has no implementation (as per the docs, "The class Object does not itself implement the interface Cloneable")
So where does my shallow clone come from? Where is the code that implements bar.clone()
if Object.clone()
has no implementation? I'm confused.
The Cloneable interface itself is empty; it is just a marker interface used by Java to ensure that using the clone method is legal. Doing it this way also removes the ability to make use of generics to ensure type safety: class Foo implements Cloneable { // Valid.
That's the reason to have protected methods in Object -- so that classes can use the method internally, but outside code cannot invoke that method on it. And the Cloneable interface has nothing at all to do with the fact Object. clone() is protected.
Cloneable interface must be implemented by the class whose object clone we want to create. If we don't implement Cloneable interface, clone() method generates CloneNotSupportedException. The clone() method is defined in the Object class.
Cloneable is an interface that is used to create the exact copy of an object. It exists in java. lang package. A class must implement the Cloneable interface if we want to create the clone of the class object. The clone() method of the Object class is used to create the clone of the object.
Be very careful using clone. In fact, I would avoid it completely. I have never needed it. BUT... that being said, the best discussion of the topic I have ever read is by Joshua Bloch, in Effective Java. Read Item 11: "Override clone judiciously".
PLEASE do yourself a favor and read that item. I actually recommend reading that entire chapter (and the rest of the book). Everything you need to know about clone and why I caution you about it is in there.
Hope this helps.
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