+1 vote

Could someone give an explanation to what is cloning concept in java with a simple example program?

asked Jul 21, 2015 in Computer Science - IT by T.PRATHIBA
recategorized Aug 24, 2015 by slow_learner | 162 views

2 Answers

+2 votes
Selected Ans.

A clone is an exact copy of the original. In java, it essentially means the ability to create an object with similar state as the original object.

The clone() method saves the extra processing task for creating the exact copy of an object. If we perform it by using the new keyword, it will take a lot of processing to be performed that is why we use object cloning.

class Student18 implements Cloneable{  
int rollno;  
String name;  
Student18(int rollno,String name){  
public Object clone()throws CloneNotSupportedException{  
return super.clone();  
public static void main(String args[]){  
Student18 s1=new Student18(101,"amit");  
Student18 s2=(Student18)s1.clone();  //s2 is cloned here,i.e copy of s1 object
System.out.println(s1.rollno+" "+s1.name);  
System.out.println(s2.rollno+" "+s2.name);  
}catch(CloneNotSupportedException c){}  

Output:101 amit
       101 amit

the second output is from the cloned object

There are different types in cloning ,you can find them with examples here

answered Jul 23, 2015 by kevin
selected Jul 25, 2015 by T.PRATHIBA
Thank you.................
0 votes
Cloning in java means the creating the copy of the objects.A clone is the exact copy of the original i.e. state of the both the objects are same.The precise meaning of "copy" may depend on the class of the object. The clones object should not hold the same memory address of the original object. Object cloning is used because if we use new keyword then it will take a lot of processing time.
answered Jan 12, 2016 by Shikha tyagi