Java- Object Cloning Example

Concept: cloned object is copy of orignal object change in orignal will reflect in clone but vice versa is not true.

//Cloneable is an interface available in Object class
//clone method available in cloneable interface is used to generating clone of class implementing  //cloneable interface
//if you try to call clone() on a class that does not implement cloneable interface a //CloneNotSupportedException is thrown


class  Testclone  implements Cloneable
{
int a;
int b;
Testclone cloneTest()//method return type is Testclone
{
// calling clone method of Object
try{
return (Testclone)super.clone();//returning duplicate reference
}
catch(CloneNotSupportedException e)
{
return this;//?
}

}
}

class Test
{

public static void main(String ar[])
{

Testclone X1=new Testclone();

X1.a=100;
X1.b=200;

Testclone X2;
Testclone X3;
X3=X1;      // Copy Object
X2= X1.cloneTest();//now X2 is clone of X1
X2.a=1;//will not reflect in X1
X3.a=1;// will reflect on  X1




System.out.println("X1: a="+X1.a+"  b"+X1.b);//100 200
System.out.println("X2: a="+X2.a+"  b"+X2.b);//100 200
}

}

Reactions: