Cloning
Cloning
========
The process of creating exact duplicate object is called cloning.
ex:
protected native java.lang.Object clone() throws CloneNotSupportedException
A Cloneable interface is a marker interface which does not have any methods.
ex:
---
class Test implements Cloneable
{
int i,j;
Test t2=(Test)t1.clone();
System.out.println(t1.i+" "+t1.j);//10 20
System.out.println(t2.i+" "+t2.j);//10 20
}
catch(CloneNotSupportedException e)
{
e.printStackTrace();
}
}
}
Shallow cloning
----------------
The process of creating exact duplicate object is called shallow cloning.
ex:
Test t1=new Test();
Test t2=(Test)t1.clone();
ex:
---
class Test implements Cloneable
{
int i,j;
public static void main(String[] args)
{
try
{
Test t2=(Test)t1.clone();
System.out.println(t1.i+" "+t1.j);//10 20
System.out.println(t2.i+" "+t2.j);//10 20
}
catch(CloneNotSupportedException e)
{
e.printStackTrace();
}
}
}
Deep cloning
------------
The process of creating duplicate object reference is called deep cloning.
ex:
Test t1=new Test();
Test t2=t1;
ex:
class Test
{
int i,j;
System.out.println(t1.i+" "+t1.j);//10 20
System.out.println(t2.i+" "+t2.j);//10 20
}
}