Cloning is a concept used to create a new object of the existing object. It means creating another object in the memory same as the existing one by copying the content of it.

For cloning a object java vendor has provided a method i.e clone() method in the Object class which is used to clone the object.

Clone() method is defined as protected in the Object and return the Object class object. Signature of the clone() is :-

protected Object clone() throws CloneNotSupportedException

This method throws one exception i.e java.lnag.CloneNotSupportedException, that means we need to handle this exception while using clone() in our program or we need to define the same exception with the throw keyword in the sub-class. 

We need to implement Cloneable interface to that class whose object we want to clone because by implementing JVM will got to know that this class is to be cloned.Syntax for Cloneable interface :

public interface java.lang.Cloneable{}

Cloneable interface is a marker interface that means without any method or member defined or we can say that empty interface. 

There are two types of cloning possible in java

1. Shallow Cloning ( default Cloning )
2. Deep Cloning ( Manual Cloning ) 

Shallow Cloning 

It is the Default implementation of the clone() method in the Object class. If we are using clone() method then it do shallow cloning. It is used to clone the data members of the existing class but fails to clone any of the member object. To overcome this limitation of the Shallow cloning there is a concept given by the java vendor is deep cloning. 

Deep Cloning 

It is manual implementation which has to be done by user itself. As not predefined method is available so we need to write our own code to do deep cloning and it is used to fulfill the limitations of the shallow cloning as it fails to clone the object member.   

0 comments:

Post a Comment

Ads 468x60px

.

Ads

.

Featured Posts

Popular Posts

Like Us On FaceBook

Total Pageviews

Online Members

Live Traffic