Site icon TechVidvan

Object Cloning in Java

Object cloning in Java refers to creating an exact copy of an object. Creates a new instance of the current object’s class and initializes all its fields with the exact contents of the object’s corresponding fields.

Object Cloning in Java

Why use clone() method?

Additional processing tasks to generate an exact copy of the object are saved by the clone() method. If we do this using the new keyword, it will take considerable processing time, so an object clone is used.

Advantages of Object cloning in Java

Disadvantage of Object cloning in Java

Example of the clone() method (object cloning):

Let’s look at a simple example of object cloning

class Techvidvan implements Clonable{  
int rollno;  
String name;  
Techvidvan(int rollno,String name){  
this.rollno=rollno;  
this.name=name;  
}  
public Object clone()throws CloneNotSupportedException{  
return super.clone();  
}  
public static void main(String args[]){  
try{  
Techvidvan s1=new Techvidvan(101,"amit");  
Techvidvan s2=(Techvidvan)s1.clone();  
System.out.println(s1.rollno+" "+s1.name);  
System.out.println(s2.rollno+" "+s2.name);  
}
catch(CloneNotSupportedException c){}  
}  
}

Output:
101 amit
101 amit

Methods for performing object cloning in Java:

Below is a list of 3 methods to create object clones in Java:

The following methods are used to clone objects in Java: A list of 3 methods for creating object clones in Java can be found below. You must use an assignment operator in order to create a copy of the reference variable. To create a copy, use the clone method. Deep Copy using a clone() method.

Below is an implementation of the above theme:

import java.io.*;
class Techvidvan{
    int x, y;
    Techvidvan()
    {
        x = 10;
        y = 20;
    }
}
// Driver Class
class Main {
    public static void main(String[] args)
    {
        Techvidvan ob1 = new Techvidvan();
        System.out.println(ob1.x + " " + ob1.y);
        Techvidvan ob2 = ob1;
        ob2.x = 100;
        System.out.println(ob1.x + " " + ob1.y);
        System.out.println(ob2.x + " " + ob2.y);
    }
}

Creating a copy using the clone() method:

Public clone methods in one or more superclasses are required for the class whose copy of the object is to be created. Super.clone() must be called by every class that uses clone() to generate a reference to the cloned object. Java.lang is also to be implemented by the class. A cloneable interface whose object we want to clone will otherwise throw a CloneNotSupportedException when the clone method is called on an object of this class.

Syntax:

protected Object clone() throws CloneNotSupportedException

Usage of clone() method -Shallow Copy:

The clone method is able to create a completely new object with an additional hash code value, meaning it is in a separate memory location, as shown below. However, the primitives managed to generate a hard copy of the Test c object because it is part of Test2, but they still share this test object c witht1 and t2. We explicitly make a deep copy of the object variable c to deal with this, which will be discussed later.

import java.util.ArrayList;
class Techvidvan{
    int x,y;
}
class Vidvan implements Cloneable {
    int a;
    int b;
    Test c = new Test();
    public Object clone() throws CloneNotSupportedException
    {
        return super.clone();
    }
}
public class Main {
    public static void main(String args[])throws CloneNotSupportedException
    {
        Vidvan t1 = new Vidvan();
        t1.a = 10;
        t1.b = 20;
        t1.c.x = 30;
        t1.c.y = 40;
        Vidvan t2 = (Vidvan)t1.clone();
        t2.a = 100;
        t2.c.x = 300;
        System.out.println(t1.a + " " + t1.b + " " + t1.c.x + " " + t1.c.y);
        System.out.println(t2.a + " " + t2.b + " " + t2.c.x + " " + t2.c.y);
    }
}

Output:
10 20 300 40
100 20 300 40

The use of the clone’s() Deep Copy method

A new copy of the fields that are referenced will be created, and these references will be placed in the Y object if we want to create a deep copy of an X object, as well as place it into another Y object. This means that only that object and not the other object will reflect any changes made to the fields of the referenced object in object X or Y.

Below is an implementation of the above theme:

class Techvidvan {
    int x, y;
}
class Test2 implements Cloneable {
    int a, b;
    Techvidvan c = new Techvidvan();
    public Object clone() throws CloneNotSupportedException
    {
        Test2 t = (Test2)super.clone();
        t.c = new Test();
        t.c.x = c.x;
        t.c.y = c.y;
        return t;
    }
}
public class Main {
    public static void main(String args[])
        throws CloneNotSupportedException
    {
        Test2 t1 = new Test2();
        t1.a = 10;
        t1.b = 20;
        t1.c.x = 30;
        t1.c.y = 40;
        Test2 t3 = (Test2)t1.clone();
        t3.a = 100;
        t3.c.x = 300;
        System.out.println(t1.a + " " + t1.b + " " + t1.c.x + " " + t1.c.y);
        System.out.println(t3.a + " " + t3.b + " " + t3.c.x + " " + t3.c.y);
    }
}

Deep Copy vs Shallow Copy:

There are some differences between using clone() as a deep copy and using it as a shallow copy, as shown below:

Shallow copy is the method of copying an object and is followed by default when cloning. In this method, the fields of the old object X are copied to the new object Y. When copying the field of the object type, the reference is copied to Y, i.e. the object Y will point to the same place that X points to. If the value of the field is a primitive type, it copies the value of the primitive type.

Therefore, any changes made to referenced objects in object X or Y will be reflected in other objects.

Shallow copies are cheap and easy to make. In the above example, we created a shallow copy of the object.

Why use clone() method or what Advantages of clone method:

If we use the assignment operator to assign an object reference to another reference variable, it will point to the same address location of the old object and no new copy of the object will be created. This makes any changes to the reference variable reflected in the original object.

If we use the copy constructor, then we have to copy all the data explicitly, i.e. we have to explicitly reorder all the class fields in the constructor. But in the clone method, this work of creating a new copy is done by the method itself. To avoid further processing, we use object cloning.

Conclusion

You can create a copy of an object using the Clone() method in Java. The Cloneable interface should be used to implement the clone method; otherwise, a Clone Not Supported Exception will occur. Two categories of clone methods are considered shallow cloning and deep cloning.

Exit mobile version