Cloning in java
package govind;
public class CloningConcept implements Cloneable {
int i=10;
int j=20;
public static void main(String[] args) throws CloneNotSupportedException
{
CloningConcept cc=new CloningConcept();
CloningConcept ccobject = (CloningConcept) cc.clone();
ccobject.i=888;
ccobject.j=999;
System.out.println(cc.i+" " +cc.j);10 20//it means no changes in original copy
System.out.println(ccobject.i+" " +ccobject.j);//888 999
}
}
o/p:-----------------
10 20
888 999
====================================================================================================================================
package govind;
public class Cat {
int j;
public Cat(int j) {
super();
this.j = j;
}
}
class Dog implements Cloneable
{
Cat c;
int i;
public Dog(Cat c, int i) {
super();
this.c = c;
this.i = i;
}
public Object clone() throws CloneNotSupportedException
{
return super.clone();
}
}
package govind;
public class ShallowCloningExample {
public static void main(String[] args) throws CloneNotSupportedException {
Cat c1=new Cat(20);
Dog d1=new Dog(c1, 10);
Dog d2 = (Dog)d1.clone();
d2.i=888;
d2.c.j=999;
System.out.println(d1.i+"--------"+d1.c.j);//10 999 //in the case of reference variable changing is done inside original copy in shallow cloning
System.out.println(d2.i+"---------"+d2.c.j);//888 999
}
}
o/p:------------------------------------------
10--------999
888---------999
=============================================================================================================================================
package govind;
public class CatClass {
int j;
public CatClass(int j) {
super();
this.j = j;
}
}
class DogClass implements Cloneable
{
CatClass cc;
int i;
public DogClass(CatClass cc, int i) {
super();
this.cc = cc;
this.i = i;
}
public Object clone() throws CloneNotSupportedException
{
CatClass c=new CatClass(cc.j);
DogClass d=new DogClass(c, i);
return d;
}
}
package govind;
public class DeepCloningDemo {
public static void main(String[] args) throws CloneNotSupportedException {
CatClass cc=new CatClass(20);
DogClass dc1=new DogClass(cc, 10);
System.out.println(dc1.i+" "+dc1.cc.j);//10 20
DogClass dc2 = (DogClass) dc1.clone();
dc2.i=888;
dc2.cc.j=999;
System.out.println(dc1.i+" "+dc1.cc.j);//10 20 original object not changed in deep cloning
System.out.println(dc2.i+" "+dc2.cc.j);//888 999
}
}
0/p:--------------------
10 20
10 20
888 999
No comments:
Post a Comment