What is the use of cloneable interface in java?

落爺英雄遲暮 提交于 2019-11-28 01:09:13
Bhesh Gurung

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.

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.

ioreskovic

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

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

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!