Brief introduction of Object cloning

Posted By : Ved Prakash | 23-May-2018

Cloning object means creating duplicates copy with current object state is called object cloning.
To perform cloning we must call Object class clone() method.

 

Prototype of clone method 

 

protected native Object clone() throws CloneNotSupportedException

 

Rule=> To execute clone() method on an object its class must be subclass of java.lang.Cloneable interface , else this method throws exception "java.lang.CloneNotSupportedException".

 

what is Cloneable interface?

 

Cloneable is a marker interface which is an empty interface. It provides permission to execute clone() method to clone the current object.

 

Why should we implementing cloneable interface when we do not implement any method?

 

To prvide permission to execute clone() method logic on this class instance.

 

Programming rule in calling clone() method 

 

1). Because clone() method is protected ,it can be called on a class object only inside that class. If we call it in another classes including in subclass it leads to CE. To call it from other class we must override clone() method in that subclass with public keyword.
2). because it is returning that object as java.lang.Object type. We must cast the clone() method returned object to its current object class.
3). clone() method's calling method should handled CloneNotSupportedException either by catching it using try/catch or by reporting it using throws keyword.
4).To execute clone() method the current object should be Cloneable type else it leads to execute CloneNotSupportedException.

 

Below program shows overriding clone() method in Example class to clone its objects in user classes.

 

Example.java
class Example implements Cloneable 
{
int x= 10 , y = 20 ;
public Example clone() throws CloneNotSupportedException
{
return (Example)super.clone();
}
}            
 
Now Test class can be compiled and executed without errors and more over we no need to downcast the cloned object to Example since we implemented covarient returns.
 
Test.java
class Test
{
public static void main(String[] args)throws CloneNotSupportedException
{
Example e1 = new Example();
Example e2 = e1.clone();
System.out.println(e1);
System.out.println(e2);
}
}       

About Author

Author Image
Ved Prakash

Ved Prakash have good knowledge in core java(oops , Collections,Exception Handling,String Handling ) and basic knowledge of J2ee(Servlets and Jsp).

Request for Proposal

Name is required

Comment is required

Sending message..