I have a simple program to clone a object , I googled the error “Exception in thread “main” java.lang.CloneNotSupportedException:” but need your help to understand the error, why am I not able to get clone of obj1?
public class Test{
int a;
int b;
public Test(int a , int b){
this.a=a;
this.b=b;
}
public static void main(String[]args) throws CloneNotSupportedException{
Test obj1=new Test(2, 4);
Test obj2=(Test) obj1.clone();
}
}
The problem occurs because the class
Testdoesn’t implement theCloneableinterface. As stated in the API specs,To fix, try something like:
Since the
Cloneableinterface declares no methods (it’s called a marker interface, just likeSerializable), there’s nothing more to do. The instances of yourTestclass can now be cloned.However, the default cloning mechanism (ie, that of
Object) might not be exactly what you are looking for, and you might want to override theclone()method. The default is to make a shallow copy, that is, you will get a new, distinct instance of your class, but the fields of both instances will refer to the same objects! For example:The last line will modify both c2 and c2clone because both point to the same instance of c1. If you want the last line to modify only c2, then you have to make what we call a deep copy.