Skip to content
Related Articles

Related Articles

Java Program to Show Shallow Cloning and Deep Cloning
  • Last Updated : 13 Jan, 2021

The default version of the clone method creates a shallow copy of an object. In java being object-oriented, object copying is creating a copy of the existing object, so the object copied can be a similar copy of the exact copy of the object of which it is copied. There are 2 ways to copy an object as follows:

In C/C++ there

Methods of Copying

Now, copying can be of three types as follows:

  1. Shallow copy
  2. Deep copy
  3. Conning

Generally, deep copy and cloning is referred to as the same deep cloning as the difference between them is a thin line where focus is laid to ease for copying objects manually using the clone() method.



1. Shallow Copy/ Cloning

  •  Default implementation while using the clone() method a shallow copy of the object is created. It means it creates a new instance and copies all the fields of the object to that new instance where both are referencing to the same memory in heap memory. 
  • clone() method of the object class supports the shallow copy of the object. If the object contains primitive as well as non-primitive or reference type variable in shallow copy, the cloned object also refers to the same object to which the original object refers as only the object references get copied and not the referred objects themselves. In simpler terms, One object is being created here while two references in the stack memory. 
  •  It returns it as an object type, we need to explicitly cast it back to our original object. This is a shallow copy of the object.

Illustration: Shallow copying object ‘t2’

class GFG 
  {
  int i,j;
  }
main(String[] args) 
  {
  // Copying
  GFG object1 = new GFG() ; 
  object.i = 5;
  object.j = 6;
  GFG object2 = object1 ;    // shallow copying object
  }     

 Example 1

Java




// Java Program to show shallow clonning
  
// Importing java input/output classes
import java.io.*;
  
// Class
class GFG {
  
    // Main driver method
    public static void main(String[] args)
    {
        // t1 and t2 objects are used to
        // illustrate shallow copy
  
        // t1 is first objecct created in heap memory
        GFG t1 = new GFG();
  
        // Creating only one object(t1) and
        // both objects (t1,t2) are pointing to only one
        // object
        GFG t2 = t1;
  
      // Display message 
        // return true if reference is same that is shallow copy
        // false if different
        // Should be returning - true 
        System.out.print(
                "Output: False if Deepcopy & True if shallow : ");
                System.out.println(t1 == t2);
    }
}
Output
Output: False if Deepcopy & True if shallow : true

Output explanation:

  1. As seen above there were two reference variables t1, t2. Whenever the object of GFG class is created the t1 (reference variable) is pointing to one object.
  2. Afterward, assigning the t1 reference variable into the new reference variable t2 of the same class pointing to the same object in heap memory. Both t1 and t2 reference variables are pointing to only one object.
  3. It does not create a new duplicate object. The above two statements prove that both t1 and t2 reference variables are point only one object.

2. Deep copy/ cloning is the process of creating exactly the independent duplicate objects in the heap memory and manually assigning the values of the second object where values are supposed to be copied is called deep cloning.

  • Whenever there is a need self copy not using default implementation is referred to as deep copy where the object to be needed is implemented as per needs. Therefore, for the deep copy, it needs to ensure that all the member classes also implement the Cloneable interface because of overriding the clone() method of the object class.
GFG object1 = new GFG() ; || Creatin object of GFG class
object.i = 5;
object.j = 6;
GFG object2 = new GFG;    || Creating another object class
object2.i = object1.i ;   || Deep copying 
object2.j = object1.j ;   || Deep copying

Note: In can not directly call clone() method using ibject.clone() as clone method in Object class of java is protected. So override the function by making access modifier as public in return super.clone() from the class created to override 

Example 2          

Java




// Java Program to show Deep Clonning
  
// Importing java input/output libraries
import java.io.*;
  
// Class
public class GFG implements Cloneable {
  
  // Defining a method as clone method is protected 
  // Defining within the class called clonnable interface 
  public Object clone() throws CloneNotSupportedException
  {
  return (GFG)super.clone(); 
  }
    
    // Main driver method
    public static void main(String[] args) throws CloneNotSupportedException
    {
        // Creating first object of GFG class
        GFG t1 = new GFG();
  
        // Using clone()  mathod to create dublicate object
        // of t1 reference variable
        // else for every object manually object needs
        // to be copied in deep copying
        // clone() ease this manual effort
        GFG t2 = (GFG)t1.clone();
  
        // Comparing two objects just after deep copying
        // Returning true for shallow(by default) copying
        // Returning false for deep copying
        System.out.println(t1 == t2);
    }
}
Output
false

Output explanation:

  1. Here, there are two reference variables t1, t2. When the object of GFG class is created, the t1 (reference variable) is pointing to one object.
  2. Afterward, t1 is assigned as a reference variable and calls clone() method into a new reference variable t2 of the same class. Both t1 and t2 reference variables are pointing to different objects. Here t2 has created a new duplicate object and t1 also.
  3. The above two statements prove that both t1 and t2 reference variable are point difference object if t1 point to O1 object than t2 point to O2 object.

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :