It is the manually implemented coding for doing cloning. This concept has came to overcome the limitation found with shallow cloning which fails to clone the data member. Through deep cloning we can be able to cover up the problem with the shallow cloning. Now with the help of deep cloning we can able to clone the object members as well but to achieve this we don't have any predefined method, so we need to write our own code. Deep Cloning is just a term to indicate that we are also cloning the object members.

To achieve deep cloning we need to override the clone method and need to create an object of the object member so that we have other object  and need to copy return that object to the clone object.

See the example below then you will be more clear about the above statement written.

Example showing Deep Cloning

class E{
    int y=40;
    String s1="tutorial";
    public E(int y2, String s12) {
 this.y=y2;
 this.s1=s12;
   }
   public E(){}
 }

public class deepCloning implements Cloneable{

    int x= 20;
    String s="java";
    E e;
  
   deepCloning(int x2, String s2, E e1){ //To initialize the property 
 this.x=x2;
 this.s=s2;
 this.e=e1; 
   }
   public deepCloning() {
 e=new E();
   }
   protected Object clone(){   //overridden clone() method 
 deepCloning d2=null;
 E e1= new E(this.e.y,this.e.s1);
 d2=new deepCloning(this.x,this.s,e1);
 return d2;
   }

public static void main(String[] args) {

        deepCloning d = new deepCloning();
 deepCloning d1=null;
 try{
  d1=(deepCloning)d.clone();// Cloning statement 
 }catch(Exception e){
  e.printStackTrace();
 }
 System.out.println(d);
 System.out.println(d1);
 d1.e.y=30;
 System.out.println(d1.e.y);
 System.out.println(d.e.y);

 }  
}

In the above code we can see that clone method is overridden to our class in which we try to create and separate object for the class E and also create and object of the current object to return the class E object so that the clone object will have that reference value for its Object member. 

And all the constructor used in the respective class to initialize the property otherwise there may have chance to throw NullPointerExcpetion

0 comments:

Post a Comment

Ads 468x60px

.

Ads

.

Featured Posts

Popular Posts

Like Us On FaceBook

Total Pageviews

Online Members

Live Traffic