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 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
To
Programming rule in calling clone() method
1). Because clone() method is
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
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.
class Example implements Cloneable
{
int x= 10 , y = 20 ;
public Example clone() throws CloneNotSupportedException
{
return (Example)super.clone();
}
}
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);
}
}
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Ved Prakash
Ved Prakash have good knowledge in core java(oops , Collections,Exception Handling,String Handling ) and basic knowledge of J2ee(Servlets and Jsp).