What is the use of implementing a cloneable interface as it is a marker interface?
I can always make a public Object clone() method in my class. What is the actual p
Purpose of clone() method is create a new instance (copy) of object on which it is called. As you can see in answers for use clone method your class should implements the Cloneable interface. You can choose how implement clone , you can do shallow or deep copy for your class. You can see examples http://javapapers.com/core-java/java-clone-shallow-copy-and-deep-copy/.
That's because the clone()
method throws CloneNotSupportedException
if your object is not Cloneable
.
You should take a look at the documentation for clone() method.
Following is how clone()
method is declared in the class Object
:
protected Object clone() throws CloneNotSupportedException
Note:
Also, it's been realized that Clone
is broken. This answer here in SO explains why and how you can avoid using it.
The purpose is specified in the javadoc. It is to specify that cloning of an object of this type is allowed.
If your class relies on the built-in implementation of clone()
(provided by the Object.clone()
method), then this marker interface enables field-by-field cloning. (If you call the built-in clone method on an object that doesn't implement Cloneable
, you get a CloneNotSupportedException
.)
Making Cloneable
a marker interface was a mistake.
That said, the one thing it does is "enable" the default implementation of clone()
in Object
. If you don't implement Cloneable
then invoking super.clone()
will throw a CloneNotSupportedException
.
Some people say it's an attempt to mimic copy constructor from C++, but here's the previous similar question on StackOverflow about it: About Java cloneable