Cloning in java

Hello guys!! Welcome to flower brackets blog. Today we are going to learn cloning in java.

Cloning in java

Cloning is a method to create identical copy of an object. To clone an object java.lang.cloneable interface should be implemented by the class.

Syntax

protected Object clone() throws CloneNotSupportedException

To make a class cloneable we have to add implements cloneable to class declaration. If not CloneNotSupportedException is thrown.


Why do we use clone in java?

Cloning saves additional burden on initiating a copy of an object. For example,

java clone

Here you can see “employeeDetailsObj” object. It has two fields “Name” and “EmpID”.

Also read – how are arrays stored in memory

Name is George and EmpID is 458464. Using clone method we can create “clonedEmployeeDetailsObj” object and which contain same fields and values.

There is no operator in java for copying an object because objects are manipulated through reference variables.

Also read – array java

Assignment operator can be used to create copy, but it only duplicates reference not the object. Clone method can be used here.

public class Employee implements Cloneable
{
   int empID; 
   String empName; 

   Employee(int empID, String empName)
   { 
      this.empID = empID; 
      this.empName = empName; 
   } 

   public Object clone()throws CloneNotSupportedException
   { 
      return super.clone(); 
   }
}

public class ObjectCloning 
{
   public static void main(String[] args) 
   {
      try
      { 
         Employee emp1 = new Employee(458464, "George"); 
         Employee emp2 = (Employee)emp1.clone(); 
         System.out.println(emp1.empID + " " + emp1.empName); 
         System.out.println(emp2.empID + " " + emp2.empName); 
      }
      catch(CloneNotSupportedException cns)
      {

      }
   }
}

Output:

458464 George
458464 George


Advantages of java cloning

  • Easy and efficient way to copy objects.
  • Fastest means to copy objects.
  • No need to write lengthy code to copy objects. One line of code is enough.

Disadvantages of java cloning

  • We can’t create constructor and there can be any number of object created.
  • It is protected hence have to provide our own clone method.
  • In the code, first we have to implement Cloneable interface, define clone() method, handle CloneNotSupportedException and lastly Object.clone().
  • Cloneable interface does not have any methods. JVM does not execute code without this interface.
  • It supports shallow copy.

Related Posts