Cloning of an object using clone() method of Object class

Shubham Maurya :

If the class which Object is being cloned contains a non-primitive data type like Object of another class then changes made in this object reflects in both the objects (i.e. Original and and Cloned Object)? While changes made in primitive data types reflects only in cloned object why?

import static java.lang.System.*;

class Best
{
    int x;
    int y;
}

class Test implements Cloneable
{
    int a;
    int b;
    Best bt = new Best();

    public Object clone()throws CloneNotSupportedException
    {
    return super.clone();   
    }
}

public class Check 
{
    public static void main(String [] args) throws CloneNotSupportedException
    {
        Test t1 = new Test();
        t1.a=20;
        t1.b=30;
        t1.bt.x = 300;
        t1.bt.y = 200;

        Test t2 = (Test)t1.clone();

        t2.a=50; //change reflects only in cloned object
        t2.bt.x = 500; //change reflects in both original and cloned object

        out.println(t1.a+" "+t1.b+" "+t1.bt.x+" "+t1.bt.y);
        out.println(t2.a+" "+t2.b+" "+t2.bt.x+" "+t2.bt.y);
    }
}
Greg Mc :

The Java clone() method only creates a shallow copy, which means that primitive data type fields have their values copied, but object type fields have their references copied. In your example, this results in the two objects "sharing" the one Best object.

To accomplish a deep copy, where a new object is created rather than referencing the existing object, you would need to create a new Best object in the overridden clone() method and either assign the values manually or make Best cloneable as well. I prefer to make Best cloneable because changing the Best class's fields does not require changing the Test class's clone() method. The most important thing when trying to create a deep copy this way is that you must always clone down until you reach only primitive data fields, which isn't always reasonable/possible. If that's the case, just assign the values manually.

Making Best cloneable:

class Best implements Cloneable
{
    int x;
    int y;
    public Object clone() throws CloneNotSupportedException
    {
        return super.clone();   
    }
}

class Test implements Cloneable
{
    int a;
    int b;
    Best bt = new Best();

    public Object clone()throws CloneNotSupportedException
    {
        Test t = (Test) super.clone();
        t.bt = (Best) this.bt.clone();
        return t;   
    }
}

Assigning the values manually:

class Best
{
    int x;
    int y;
}

class Test implements Cloneable
{
    int a;
    int b;
    Best bt = new Best();

    public Object clone()throws CloneNotSupportedException
    {
        Test t = (Test) super.clone();
        t.bt.x = this.bt.x;
        t.bt.y = this.bt.y;
        return t;   
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=140843&siteId=1