Example of Deep Cloning in java


We write a program which is example of shallow cloning. Here we are write code for four class first is JFC1.java, second is JFC2.java, third DeepCloning.java and fourth is TestDeepCloning.java.

Now see the code of these class.


Class JFC1.java



package com.javaforecast4u;

public class JFC1 {
    int x;
     JFC1(int x)
     {
      this.x=x;
     }
}

Class JFC2.java

package com.javaforecast4u;

public class JFC2 {

     int y;
     JFC1 obj;
     JFC2(int y,JFC1 obj)
     {
      this.y=y;
      this.obj=obj;
     }
}

Class DeepCloning.java

package com.javaforecast4u;

public class DeepCloning implements Cloneable {

    /**
     * @author :arbind
     */
    int z;
     JFC2 obj;
     DeepCloning(int z,JFC2 obj)
     {
      this.z=z;
      this.obj=obj;
     }
    void show()
    {
     System.out.println(this.obj.obj.x);
     System.out.println(this.obj.y);
     System.out.println(z);
    }
    public Object clone()
    {
     JFC1 cobj=new JFC1(this.obj.obj.x);
     JFC2 bobj=new JFC2(this.obj.y,cobj);
     DeepCloning aobj=new DeepCloning(this.z,bobj);
     return aobj;
    }

     }
   
Finally we write a class for testing.


package com.javaforecast4u;
public class TestDeepCloning {
    public static void main(String as[])
     {
      JFC1 cobj=new JFC1(10);
      JFC2 bobj=new JFC2(20,cobj);
      DeepCloning dc1=new DeepCloning(30,bobj);
      DeepCloning dc2=(DeepCloning)dc1.clone();
       System.out.println("Original Object:-");
       dc1.show();
     System.out.println("Cloned objects");
     dc2.show();
     System.out.print("1st level object & cloned object points same object:-");
      System.out.println(dc1==dc2);
      System.out.print("2nd level object & cloned object points same object:-");
      System.out.println(dc1.obj==dc2.obj);
      System.out.print("3rd level object & cloned object points same object:-");
      System.out.println(dc1.obj.obj==dc2.obj.obj);
      dc2.obj.obj.x=100;
      dc2.obj.y=200;
      dc2.z=300;
     System.out.println("after changing the values of cloned object ");
     dc2.show();
     DeepCloning dc3=(DeepCloning)dc2.clone();
      System.out.println("values of 1st cloned objects:-");
      dc2.show();
     System.out.println("values of 2nd cloned objects:-");
     dc3.show();
     System.out.println("values of original objects:-");
     dc1.show();
}
}

0 comments :

Post a Comment