As per java.lang.Cloneable interface:
The documentation for the Cloneable says –
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.
But the following code is working correctly. It is not giving any error when I call ex1.clone.
package com.sriPushpa.thread;
public class exceptionHandling implements Cloneable {
int a = 10;
public static void main(String args[]) {
exceptionHandling ex1 = new exceptionHandling();
exceptionHandling ex2 = null;
try {
ex2 = (exceptionHandling) ex1.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
System.out.println("SUCCESS");
}
}
The
clone()method is implemented byjava.lang.Object, as a protected method. Your code works because you’re calling theclone()method from the same class as the one you clone.If you want your object to be cloneable, you should override the
clone()method and make it public:Note that the doc doesn’t say that implementing the Cloneable interface will always make
clone()fail. It says that implementing it is not a guarantee thatclone()will work. This is very different.