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

  • The java.lang page. The class whose object clone we want to create must implement the cloneable interface.
  • CloneNotSupportedException is thrown by the clone() method if we don’t implement a cloneable interface.
  • The object class defines a clone() method. The clone() method derives from the following syntax: CloneNotSupportedException is thrown in the clone() method of the protected object.

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

  • Although there are some design issues with Object.clone(), it is still the simplest and most widely used method for copying objects. Below is a list of benefits that can be derived from using clone():
  • No need to write long and repetitive code. Use an abstract class with a four- or five-line clone() method.
  • This is the easiest and fastest way to copy objects, especially when we use them for a project that is already in development or older.
  • To complete this task, just specify a parent class, implement Cloneable in it, and provide a definition of the clone() method.
  • The most efficient way to copy an array is with Clone().

Disadvantage of Object cloning in Java

  • The following section lists the disadvantages of clone(): Many syntax changes are needed when using Object.clone(). methods such as implementing the cloneable interface, defining the clone() method, handling any CloneNotSupportedException, and calling object.clone().
  • The interface is not supported by any method, so we need to create a cloneable interface. For example, call to show the JVM that we can clone our object.
  • Clone.clone() was protected, so we need to call Object.clone(). of it using our own clone or by calling Object.clone() indirectly. Object.clone() doesn’t have a constructor, so we can’t control the creation of objects.
  • Each of their superclasses should define a clone() method or inherit from another superclass if you want to write a clone method in one of your child classes. If not, that’s great. Clone() will not work because the string is broken.
  • Object.clone() is not intended for simple copying but should be overridden in case we need deep cloning.

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:

  • To create a copy of a reference variable, you must use the assignment operator.
  • Using the clone() method to create a copy. Using the clone() method for Deep Copy.

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.