Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I must override clone if i want cloneable class?

Tags:

java

object

clone

Why I must override clone if i want cloneable class? All classes extends from Object, so why I must override the Object clone method? Why I cant just invoke the original Object clone method?

like image 317
Shelef Avatar asked Mar 18 '13 12:03

Shelef


People also ask

Why do we need to override clone method?

Because, for a class to be cloned, you need to implement the Cloneable interface. And then your class uses the clone method of Object class instead. Because, Cloneable interface doesn't exactly have any method for cloning . It would be a better option to use Copy Constructor instead.

Why clone method is not in cloneable interface?

clone method produces an instance of whatever class it is called on; this cannot be reproduced without native code. This is why the Object. clone method could not have been avoided. Cloneable could have contained a clone method, but it would create issues regarding the throws clause.

Is it necessary to override clone method in Java?

Java Object Cloning Cloneable marker interface. Otherwise, it will throw CloneNotSupportedException at runtime. Also Object clone is a protected method, so you will have to override it. Let's look at Object cloning in Java with an example program.

Why should we implement cloneable interface if we have to clone an object though clone method comes from object class?

Cloneable is a marker interface. The clone() method isn't defined by the Cloneable interface. The clone method in the Object class is protected to prevent a client class from calling it - Only subclasses can call or override clone, and doing so is a bad idea.


2 Answers

It's one of the many "design flaws" in the JDK.

Clonable should have been an interface with a clone() method, but instead it's a marker interface and Object has a "do nothing" implementation of the clone() method... and you're left with your question.


If you're interested, this answer lists some other "mistakes" in java.

like image 70
Bohemian Avatar answered Sep 23 '22 23:09

Bohemian


See here: http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Cloneable.html

Invoking Object's clone method on an instance that does not implement the Cloneable interface results in the exception CloneNotSupportedException being thrown.

Also I guess this discussion would be helpful for you: Confusion about cloneable interface and object.clone() in java

like image 26
Rush Avatar answered Sep 21 '22 23:09

Rush