Example of Shallow 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 ShallowCloning.java and fourth is Test1shallowCloning.java.

Now see the code of these class.



package com.javaforecast4u;

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


}

Second Class is:

package com.javaforecast4u;

public class JFC2 {

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

}

and third is:


package com.javaforecast4u;

public class ShallowCloning implements Cloneable {

    /**
     * @author :arbind
     */
    int z;
     JFC2 obj;
     ShallowCloning(int z,JFC2 obj)
     {
      this.z=z;
      this.obj=obj;
     }

     ShallowCloning myclone()
    {
     Object o=null;
     try{
        o=this.clone();
        }catch(Exception e){
        e.printStackTrace();
        }
        ShallowCloning a1=(ShallowCloning)o;
        return a1;
         }
     }
   
And class class is:

package com.javaforecast4u;

public class Test1shallowCloning {
    public static void main(String as[])
     {
      JFC1 cobj=new JFC1(10);
      JFC2 bobj=new JFC2(20,cobj);
      ShallowCloning a1=new ShallowCloning(30,bobj);

      ShallowCloning a2=a1.myclone();
     
      System.out.println(a1==a2);
      System.out.println(a1.obj==a2.obj);
      System.out.println(a1.obj.obj==a2.obj.obj);
     }

}
  

0 comments :

Post a Comment