Confusion about cloneable interface and object.clone() in java

ambertch picture ambertch · Jul 1, 2009 · Viewed 22.2k times · Source

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.

Answer

Tom picture Tom · Jul 1, 2009

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.