HomeTagSubmit NotesAsk AnythingLoginSubscribe Us
1. Feel Free to ask and submit anything on and get satisfactory answer
2. Registration is not compulsory, you can directly login via google or facebook
3. Our Experts are looking for yours ?.

corejava-OOPs: What is object cloning?

What is the use of object cloning? Please explain me with suitable example.

corejava x 353
OOPs x 49
Posted On : 2013-11-23 18:21:00.0
profile Saksham Kumar - Saksham Kumar


The object cloning is a way to the create exact copy of an object. clone() method of Object class is used to clone an object.
The java.lang.Cloneable interface must be implemented by the class whose object clone we want to create. If we don´t implement Cloneable interface, clone() method generates

********************** Syntax of the clone() method is as follows ***********************
protected Object clone() throws CloneNotSupportedException

=================== Why use clone() method ? =====================

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.

******************** Let´s see the simple example of object cloning ********************

class Student implements Cloneable{
int rollno;
String name;

Student(int rollno,String name){

public Object clone()throws CloneNotSupportedException{
return super.clone();

public static void main(String args[]){
Student s1=new Student(101,"amit");
Student s2=(Student)s1.clone();

System.out.println(s1.rollno+" ";
System.out.println(s2.rollno+" ";

}catch(CloneNotSupportedException c){}

========================= Output =============================
101 amit
101 amit

As you can see in the above example, both reference variables have the same value. Thus, the clone() copies the values of an object to another. So we don´t need to write explicit code to copy the value of an object to another.

If we create another object by new keyword and assign the values of another object to this one, it will require a lot of processing on this object. So to save the extra processing task we use clone() method.

Posted On : 2013-11-23 18:37:37
Satisfied : 1 Yes  0 No
profile Rishi Kumar - Rishi Kumar
Reply This Thread

Post Answer
Please Login First to Post Answer: Login login with facebook -