Jyotirup
Jyotirup

Reputation: 2920

What is the use of cloneable interface in java?

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 purpose of cloneable interface?

Upvotes: 7

Views: 22298

Answers (5)

Bhesh Gurung
Bhesh Gurung

Reputation: 51030

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.

Upvotes: 7

Stephen C
Stephen C

Reputation: 718768

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

Upvotes: 2

Sergey Gazaryan
Sergey Gazaryan

Reputation: 1043

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

Upvotes: 2

ioreskovic
ioreskovic

Reputation: 5699

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

Upvotes: 2

Laurence Gonsalves
Laurence Gonsalves

Reputation: 143124

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.

Upvotes: 5

Related Questions