Reputation: 47
I am having a class whose object I want to clone. I did that by implementing the Cloneable interface and overriding the clone method. But if I am creating a clone method, without implementing the Cloneable interface, it is throwing an exception. What super power does this Marker Interface (Cloneable) is providing to my class?
Upvotes: 0
Views: 920
Reputation: 5173
It allows cloning according to the JavaDoc of Object.clone
:
First, if the class of this object does not implement the interface
Cloneable
, then aCloneNotSupportedException
is thrown.
Everytime you call Object.clone()
this requirement is verfied.
The JavaDoc of Cloneable
itself says:
A class implements the
Cloneable
interface to indicate to theObject.clone()
method that it is legal for that method to make a field-for-field copy of instances of that class. Invoking Object's clone method on an instance that does not implement theCloneable
interface results in the exceptionCloneNotSupportedException
being thrown.
Summarizing it:
It's part of the specified behavior. Not complying with this requirement will be obvoius at runtime.
Upvotes: 0
Reputation: 3232
Cloning of objects in java :
There is the Cloneable
interface. You would expect the interface to have a clone() method, which would return a copy of the object. But, it is not the case. Cloneable
is just a marker interface. That means, it has no methods whatsoever, it just marks the class as suitable for cloning. The clone
method is present on the Object
class instead.
Upvotes: 0