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?
- 
                    The same way `Serializable` writes objects to disk, despite it being a marker interface. – Elliott Frisch Oct 16 '18 at 10:32
- 
                    [This answer](https://stackoverflow.com/a/4081982/6395627) to the duplicate explains how implementing `Cloneable` works. The interface is simply telling the _native_ `Object.clone` method, "hey, you can clone me". Without the interface the method will refuse to clone the object (by throwing an exception). As mentioned by Elliot, this is similar to how `Serializable` is used. – Slaw Oct 16 '18 at 11:59
2 Answers
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.
 
    
    - 3,132
- 3
- 20
- 39
It allows cloning according to the JavaDoc of Object.clone:
First, if the class of this object does not implement the interface
Cloneable, then aCloneNotSupportedExceptionis thrown.
Everytime you call Object.clone() this requirement is verfied.
The JavaDoc of Cloneable itself says:
A class implements the
Cloneableinterface 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 theCloneableinterface results in the exceptionCloneNotSupportedExceptionbeing thrown.
Summarizing it:
It's part of the specified behavior. Not complying with this requirement will be obvoius at runtime.
 
    
    - 5,055
- 2
- 18
- 34
