Object Cloning in Java

Object Cloning in Java


To create an exact copy of an object is known as object cloning in java. The clone () method of object class is used to create an exact copy of an object in java. If we want to create a clone of an object then the java.lang.Cloneable interface should be implemented. The clone () method in java is defined in the object class.

The following is the syntax of the clone () method in Java:

protected Object clone() throws CloneNotSupportedException


Why use clone () method?

In Java programming language the clone method is used to create an exact copy of the object and to save the processing task to create an exact copy of the object. The clone of an object can be created by using the new keyword but it will take a lot of time and hence we use the clone () method in java.


Advantage of object cloning:

Through object clone () method we can save a lot of time. The clone () method takes less processing task to create a copy of an object. In this way memory and time to perform tasking will be saved.


Example of clone () method:

Consider the following example in which clone of object is created by using the clone () method:

CODE:

class Employee implements Cloneable {

int id;

String name;

Employee (int id, String name) {

this. id = id;

this. name = name;

}

public object clone () throws CloneNotSupportedException {

return super. clone ();

}

public static void main (String args []) {

try {

Employee z = new Employee (122, “Stuart”);

Employee z1= (Employee) z. clone ();

system. out. println (z. id + “” + z. name);

system. out. println (z1. id + “” + z1. name);

}

catch (cloneNotSupportedException c) {}

}

}

OUTPUT:

122 Stuart

122 Stuart

In the above example, the clone of the object “z” of the class employee is created by using the clone () method. Now the object z1 is the clone or the exact copy of the object z and when we used the object z1 to call the data members we got the same output.

In other words we can say that the reference variables have the same value. The clone () method copied the value of one object to the other. In this way we do not need to write an explicit code to copy the contents of one object to other.