0% found this document useful (0 votes)
3 views3 pages

Cloning

Uploaded by

bybit1sai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views3 pages

Cloning

Uploaded by

bybit1sai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 3

Cloning

========
The process of creating exact duplicate object is called cloning.

The main objective of cloning is to maintain backup.

To perform cloning we need to use clone() method of Object class.

ex:
protected native java.lang.Object clone() throws CloneNotSupportedException

We can perform cloning only for cloneable objects.

To create a cloneable object a class must implements Cloneable interface.

A Cloneable interface is a marker interface which does not have any methods.

ex:
---
class Test implements Cloneable
{
int i,j;

public static void main(String[] args)


{
try
{

Test t1=new Test();


t1.i=10;
t1.j=20;

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();
}
}
}

Q) Difference between shallow cloning and deep cloning ?

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 t1=new Test();


t1.i=10;
t1.j=20;

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;

public static void main(String[] args)


{

Test t1=new Test();


t1.i=10;
t1.j=20;
Test t2=t1;

System.out.println(t1.i+" "+t1.j);//10 20
System.out.println(t2.i+" "+t2.j);//10 20

}
}

You might also like