Nayan Arora
Nayan Arora

Reputation: 47

How does implementing Cloneable interface allows cloning of objects, as it is a Marker Interface and doesn't have any methods?

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

Answers (2)

LuCio
LuCio

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 a CloneNotSupportedException 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 the Object.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 the Cloneable interface results in the exception CloneNotSupportedException being thrown.

Summarizing it:
It's part of the specified behavior. Not complying with this requirement will be obvoius at runtime.

Upvotes: 0

Khalid Shah
Khalid Shah

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

Related Questions