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?
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.
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.
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.
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.
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.
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
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