Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

cloneable

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.

like image 250
ambertch Avatar asked Jul 01 '09 05:07

ambertch


People also ask

Why clone method is not in cloneable interface?

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.

Why is object clone () method available only to classes that implement cloneable interface?

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.

How are cloneable interface CloneNotSupportedException and clone () method are related?

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.

What is cloneable interface in java?

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.


1 Answers

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.

like image 150
Tom Avatar answered Oct 15 '22 03:10

Tom