Clone in Java

The act of making an exact duplicate of an object is referred to as object cloning. It makes a brand-new instance of the current object's class and fills all of its fields exactly with the data found in the corresponding row or column of the current object. In this article, we will talk about cloning in Java and detail it along with the clone() method in Java. We will also discuss the advantages and disadvantages of the clone() method and learn how to create a copy of an item using clone() in java.

 Introduction of Clone in Java

An exact duplicate of an object can be made by using object cloning. An object can be duplicated using the Object class's clone() function. 

For the class with the object for which we wish to clone, we must implement a Cloneable interface for that. CloneNotSupportedException is produced by the clone() method if the Cloneable interface is not implemented.

The clone() method eliminates the need for additional processing to make an exact duplicate of an object. We utilize object cloning since performing it via the new keyword would need a substantial portion of processing time.

The Object class contains a definition for the clone() method. The clone() method has the following syntax:

Clone in Java

Wish to make a career in the world of Java? Start with HKR'S Java Training

Properties of clone() method

Let us see a few properties of the clone() method:

  • No parameters are required for the clone() function.
  • Considering that clone() returns a duplicate of the object
  • If the class of the object doesn't implement the Cloneable interface, it will raise a CloneNotSupportedException exception.
  • Cloneable is not implemented by the Object class. As a result, we are unable to call a clone() method on an Object class object.

Let us see a Java code below to understand the working of clone() method in Java in a better manner:

class Main implements Cloneable {


  String name;

  int version;

  public static void main(String[] args) {


    Main object1 = new Main();

    object1.name = "iPhone";

    object1.version = 13;

    

    System.out.println(object1.name);  

    System.out.println(object1.version);  


    try {


      Main object2 = (Main)object1.clone();


      System.out.println(object2.name);    

      System.out.println(object2.version);   

    }

    catch (Exception x) {

      System.out.println(x);

    }

  }

}

The output of this Java code will be:

iPhone

13

iPhone

13

Java Certification Training

  • Master Your Craft
  • Lifetime LMS & Faculty Access
  • 24/7 online expert support
  • Real-world & Project Based Learning

Creating a copy of clone() method

There must be a public clone() method in the class being copied, or with one of its root classes.

  • To receive the reference to the cloned object, each class that will implement clone() should call super.clone().
  • Furthermore, the class must implement Java.lang.
  • CloneNotSupportedException will be thrown if the clone method is invoked on an object of that class without first creating a clone of the object's Cloneable interface.
Shallow Copy

The clone method's default implementation will create a shallow copy of a source object, which means it creates a new instance of the Object type, replicates all the fields to it, and then returns a fresh object of the same type. This Object must be specifically typecast into the source object's object type.

All of the fields from the source object, along with the primitive class as well as the object references, will be identically duplicated in this object. A duplicate of those items is not made if the parent class contains any links to certain other objects in the field; instead, the new instance will only include links to those objects. This means that any changes we make to the shallow copy will also be applied to the source object. Both occurrences are interconnected.

Let us see an example below to understand shallow copy in a better manner

class HKRclone  

    {  

    int x = 30;  

    }  

public class ShallowCopy  

{     

public static void main(String argvs[])   



HKRclone object1 = new HKRclone();  

HKRclone object2 = object1;  

 

object2.x = 4;  

System.out.println("The value of x will be: " + object1.x);  

}  

}   

The output of this Java code will be:

The value of x will be 4
Deep Copy

We can claim that we have performed a deep copy when we duplicate an entity to make two or more identical copies which don't reflect modifications made to one entity. The other entities' memory is allocated fresh during a deep copy, and references to those other entities are not duplicated. Everything has a unique, independent reference. 

Just like a shallow copy, a deep copy is also an exact replica of an object having every field of the source object, but unlike a shallow copy, if the source object contains any references to other objects as fields, the clone method must be called in order to generate a copy of the object. This demonstrates the independence of the source and destination objects. Any modification to the cloned object has no effect on the original object.

Let us see an example of deep copy to understand it in a better manner.

class HKRclone 

{  

int x = 20;  

}  

public class DeepCopy   

{     

    public static void main(String argvs[])   

    {  

    HKRclone object1 = new HKRclone();  

 

    HKRclone object2 = new HKRclone();  

    object2.x = 6;  

    System.out.println("The value of x will be: " + object1.x);  

    }  

}   

The output of this java code will be:

The value of x will be 20

Subscribe to our youtube channel to get new updates..!

Advantages of clone() method

  • If we give the reference of an object to another variable using the assignment operator, it will refer towards the same address position as the original object and no additional copies of the object will be made. As a result, any modifications to the reference variable would cause the original object to update.
  • When using a copy function Object(), all data must be explicitly copied over, meaning all class fields must be explicitly reassigned in the function Object(). However, the clone method does all of the work involved in making a new duplicate on its own. Hence, we will use the clone() method or object cloning to prevent additional processing.
  • There's no need to create long, repeating codes. Use only abstract classes with clone() methods that are 4 or 5 lines long.
  • In particular, if the user is applying it on an existent or outdated project, it is the simplest and most effective method for copying items. The work can be completed by simply defining a parent class, implementing Cloneable within it, and providing the description of the clone() method.
  • The quickest way of copying an array is with clone().

Wish to make a career in the world of Full Stack Web Development ? Start with HKR'S Full Stack Web Development Course

Disadvantages of clone() method

  • We must implement a Cloneable interface, define the clone() method, handle the CloneNotSupportedException, and then use Object.clone() in order to use the Object.clone() function.
  • Even though clone() doesn't contain any methods, we still need to implement a cloneable interface. We only need to utilize it to inform the JVM that we're able to clone() our object.
  • Since Object.clone() is protected, we must supply our own clone() and call Object.clone() indirectly from it.
  • Since no function Object()is called by Object.clone(), we have no control over how an object is built.
  • All of a child class's superclasses must either declare the method for cloning in them or inherit it from a different parent class if the user wants to write one. The super.clone() loop won't succeed otherwise.
  • Only shallow copying is supported by Object.clone(); if deep cloning is required, we must override this function.

Top 30 frequently asked JAVA Interview Questions !

Java Certification Training

Weekday / Weekend Batches

Conclusion

In this article, we have talked about the clone() method in Java. An exact duplicate of an object can be made by using object cloning. An object can be duplicated using the Object class's clone() function. We have also discussed the properties of the clone() method along with the advantages and disadvantages of cloning in Java. We have also put some light on various clone() methods such as deep copy as well as a shallow copy. 

Related articles:

Find our upcoming Java Certification Training Online Classes

  • Batch starts on 5th Jun 2023, Weekday batch

  • Batch starts on 9th Jun 2023, Fast Track batch

  • Batch starts on 13th Jun 2023, Weekday batch

Global Promotional Image
 

Categories

Request for more information

Amani
Amani
Research Analyst
As a content writer at HKR trainings, I deliver content on various technologies. I hold my graduation degree in Information technology. I am passionate about helping people understand technology-related content through my easily digestible content. My writings include Data Science, Machine Learning, Artificial Intelligence, Python, Salesforce, Servicenow and etc.

An exact duplicate of an object can be made by using object cloning. An object can be duplicated using the Object class's clone() method. 

It is generally called a public method in java. 

It is done using CopyOf() method in Java. 

Clone means to make a new object based on an existing one. Copying is the process of moving information from one thing to another

Since it is not specified in the Cloneable interface, the clone() method is protected. The clone function is rendered relatively worthless as a result, as it may create clones of your current data.