Cloning

CLONING:


Cloning is a process of creating a copy for existing object.

Hello h1=new Hello();                       
Hello h2=h1.clone();
 If you want  to clone any class objects then you can use clone method which is implemented in object class.

Clone method is protected in object because of that it must be called  directly in the class whose object you want to clone.     
If you want to clone any class object then the class must implement Clonable interface. Clonable is a marker interface which contains no members.
When you trying to clone any class object without implementing Clonable interface then JVM throws an exception called “Clone Not Supported Exception”.
Types of cloning: ----------

  •    Shallow cloning
  •    Deep cloning 
In the shallow example only the top level object is created newly other deep level object are used as it. This type of cloning is called shallow cloning.
In the shallow example  we use clone method which is implemented in the object class so object class clone method is using shallow cloning implementation.
If you want to implement deep cloning then you have to override object class clone method in your class.
In deep cloning all the objects (top level and deep level object) will be created newly.

 A class              -----------   same
B class                ------------ same

In hello class replace myclone method with following method

Public object clone()
{
Int x=this.bobj.aobj.a;
A aa =new A(x);
Int y=this.bobj.b;
B bb=new B(y,aa);
Int z=this.x;
Hello hh=new Hello(z,bb);
return hh;
}
}


//change the code at that point

h.show();
hello h1=(Hello)h.clone();
h1.show();

0 comments :

Post a Comment