Have a Question?

If you have any question you can ask below or enter what you are looking for!

Difference between deep cloning and shallow cloning?

Difference between deep cloning and shallow cloning?

Shallow cloning VS Deep Cloning

Difference between deep cloning and shallow cloning?

Shallow cloning

  • The process of creating a bit-wise copy of an object is called shallow cloning.
  • If the main object contains primitive variable then exactly duplicated will be created in the cloned object.
  • If the main object contains any reference variable then the corresponding object won’t be created just duplicate reference will be created pointing to the old contained object.
  • Object class clone method meant for shallow cloning.
package com.java4us;

public class Test1 {
    int i;

    Test1(int i) {
        this.i = i;
    }

    public String toString() {
        return i + "";
    }
}
package com.java4us;

public class Test2 implements Cloneable {
    Test1 t;
    int j;

    public Test2(Test1 t, int j) {
        this.t = t;
        this.j = j;
    }

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

    public String toString()
    {
        return t + ".." + j;
        
    }

    public static void main(String[] args) throws CloneNotSupportedException {
        Test1 t = new Test1(10);
        Test2 t1 = new Test2(t, 20);
        System.out.println(t1);  //10..20
        Test2 t2 = (Test2) t1.clone();
        System.out.println(t2);  //10..20
        t2.t.i = 999;
        System.out.println(t1); //999..20
        System.out.println(t2); //999..20
    }

}
  • In shallow cloning by using cloned object reference if we perform any change to the contained object then those change will be reflected in the main object.
  • To overcome this problem we should go for deep cloning.

Leave a Reply

Your email address will not be published. Required fields are marked *