Quantcast
Channel: Crunchify
Viewing all articles
Browse latest Browse all 1037

How to avoid Exception in thread main – java.lang.CloneNotSupportedException

$
0
0

java.lang .CloneNotSupportedException How to avoid Exception in thread main   java.lang.CloneNotSupportedException

public interface Cloneable

I faced this exception in my previously explained post: http://crunchify.com/what-are-all-the-different-ways-to-create-an-object-in-java/

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.

By convention, classes that implement this interface should override Object.clone (which is protected) with a public method. See 

Object.clone()
 for details on overriding this method.

Note that this interface does not contain the clone method. Therefore, it is not possible to clone an object merely by virtue of the fact that it implements this interface. Even if the clone method is invoked reflectively, there is no guarantee that it will succeed.

In summary,  this can be avoided  by implementing “Cloneable” Interface and Overriding protected method clone().

java.lang .CloneNotSupportedException Implement Clonable Interface How to avoid Exception in thread main   java.lang.CloneNotSupportedException

The post How to avoid Exception in thread main – java.lang.CloneNotSupportedException appeared first on Crunchify.


Viewing all articles
Browse latest Browse all 1037

Trending Articles