Unable to understand clone

Issue

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();
       }
 }

Solution

The problem occurs because the class Test doesn’t implement the Cloneable interface. As stated in the API specs,

if the class [..] does not implement the interface Cloneable, then a CloneNotSupportedException is thrown.

To fix, try something like:

public class Test implements Cloneable { 
  ...
}

Since the Cloneable interface declares no methods (it’s called a marker interface, just like Serializable), there’s nothing more to do. The instances of your Test class 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 the clone() 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:

class C1 {
  Object o;
}
class C2 implements Cloneable {
  C1 c1;
}

... main ... {
  C2 c2 = new C2();
  c2.c1 = new C1();
  c2.c1.o = new Object();
  C2 c2clone = c2.clone();
  System.out.println(c2 == c2clone); // prints false
  System.out.println(c2.c1 == c2clone.c1); // prints true
  c2.c1.o = new Object(); // modified both c2 and c2clone!!!

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.

Answered By – Bruno Reis

Answer Checked By – Senaida (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.