Cloning

Clone ()

· The process of creating exactly duplicate object is called cloning.
· The main objective of cloning is to maintain backup.
· That is if something goes wrong we can recover the situation by using backup copy.
· We can perform cloning by using clone() method of Object class.
protected native object clone() throws CloneNotSupportedException;
Example:
class Test implements Cloneable
{
int i=10;
int j=20;
public static void main(String[] args)throws CloneNotSupportedException
{
Test t1=new Test();
Test t2=(Test)t1.clone();
t2.i=888;
t2.j=999;
System.out.println(t1.i+"---------------"+t1.j);
System.out.println(t2.i+"---------------"+t2.j);
}
}
Output:
10---------------20
888---------------999


· We can perform cloning only for Cloneable objects.
· An object is said to be Cloneable if and only if the corresponding class implements
Cloneable interface.
· Cloneable interface present in java.lang package and does not contain any methods. It is
a marker interface where the required ability will be provided automatically by the JVM.
Shallow cloning vs deep cloning:
· The process of creating just duplicate reference variable but not duplicate object is
called shallow cloning.
Example:
Test t1=new Test();
Test t2=t1;


Example:
Test t1=new Test();
Test t2=(Test)t1.clone();
System.out.println(t1==t2);//false
System.out.println(t1.hashCode()==t2.hashCode());//false


· Cloning by default deep cloning.
getClass() method:
· This method returns runtime class definition of an object.
Example:
class Test implements Cloneable
{
public static void main(String[] args)throws CloneNotSupportedException
{
Object o=new String("bhaskar");
System.out.println("Runtime object type of o is :"+o.getClass().getName());
}
}
Output:
Runtime object type of o is: java.lang. String

SHARE

About df

    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment