Object Cloning In Java
Object Cloning
In Java, the object cloning is used to create an exact copy of an object. Object class have a clone() method, which is used to clone an object.
Advantage of Object cloning
Object cloning is mainly used to less processing task in Java.
The clone() method is created in the object class.
Syntax of clone method
The java.lang.Cloneable interface should be implemented by the class, whose object clone, we want to create. If we don't implement Cloneable interface, clone() method produces an error (CloneNotSupportedException).
Let’s see an example of object cloning, given below.
Code
- public class Car implements Cloneable {
- int carno;
- String carname;
- Car(int carno, String carname) {
- this.carno = carno;
- this.carname = carname;
- }
- public Object clone() throws CloneNotSupportedException {
- return super.clone();
- }
- public static void main(String args[]) {
- try {
- Car c1 = new Car(2364588, "Swift Dezire");
- Car c2 = (Car) c1.clone();
- System.out.println(c1.carno + " " + c1.carname);
- System.out.println(c2.carno + " " + c2.carname);
- } catch (CloneNotSupportedException e) {}
- }
- }
Output
In the example, mentioned above, we have two reference variables that have the same value. Thus, the clone() copies the exact values of an object to another. Therefore, we don’t need to write the 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 with this one, it will require a lot of processing on this object. Thus, to save the extra processing task, we use clone() method.
Usage of clone method
- Saves the extra processing task.
- Create the exact copy of an object.
Summary
Thus, we learnt that object cloning is used to create an exact copy of an object and also learnt its advantages in Java.