What is deep copy? Explain with an example in Java.


Creating an exact copy of an existing object in the memory is known as cloning.

The clone() method of the class java.lang.Object accepts an object as a parameter, creates and returns a copy of it (clones).

In order to use this method, you need to make sure that your class implements the Cloneable interface.

Example

 Live Demo

import java.util.Scanner;
public class CloneExample implements Cloneable {
   private String name;
   private int age;
   public CloneExample(String name, int age){
      this.name = name;
      this.age = age;
   }
   public void displayData(){
      System.out.println("Name : "+this.name);
      System.out.println("Age : "+this.age);
   }
   public static void main(String[] args) throws CloneNotSupportedException {
      Scanner sc =new Scanner(System.in);
      System.out.println("Enter your name ");
      String name = sc.next();
      System.out.println("Enter your age ");
      int age = sc.nextInt();
      CloneExample std = new CloneExample(name, age);
      System.out.println("Contents of the original object");
      std.displayData();
      System.out.println("Contents of the copied object");
      CloneExample copiedStd = (CloneExample) std.clone();
      copiedStd.displayData();
   }
}

Output

Enter your name
Krishna
Enter your age
20
Contents of the original object
Name : Krishna
Age : 20
Contents of the copied object
Name : Krishna
Age : 20

Shallow copy

Whenever you try to create a copy of an object using the shallow copy, all fields of the original objects are copied exactly. But, if it contains any objects as fields then, only references to those objects are copied not the compete objects.

This implies that, if you perform shallow copy on an object that contains any objects as fields, since only references are copied in a shallow copy, both the original and copied object points to the same reference internally and, if you do any changes to the data using the copied object, they are reflected in the original object too.

Note − By default, the clone() method does a shallow copy.

Deep copy

Whenever you try to create a copy of an object, in the deep copy all fields of the original objects are copied exactly, in addition to this, if it contains any objects as fields then copy of those is also created (using the clone() method).

This implies that, if perform you deep copy on an object that contains reference (object), both the original and copied object refers to different objects and, if you do any changes to the data the copied object they are not reflected in the original object.

To perform field copy

Override the clone method and within it copy the reference fields using the clone() method as shown below −

protected Object clone() throws CloneNotSupportedException{
   StudentData student = (StudentData) super.clone();
   student.contact = (Contact) contact.clone();
   return student;
}

Example

In the following example the StudentData class contains a String variable (name), an integer variable (age) and an object (Contact).

In the main method we are creating an object of the StudentData class and copying it. From the copied object we are changing the data(field values) of the reference used (Contact object). Then, we are printing the data of copied object first followed by data of the original one.

Since we have done a deep copy (by overriding the clone() method), you can observe that the change done is not reflected in the original object.

 Live Demo

import java.util.Scanner;
class Contact implements Cloneable{
   private long phoneNo;
   private String email;
   private String address;
   public void setPhoneNo(long phoneNo) {
      this.phoneNo = phoneNo;
   }
   public void setEmail(String email) {
      this.email = email;
   }
   public void setAddress(String address) {
      this.address = address;
   }
   Contact(long phoneNo, String email, String address ){
      this.phoneNo = phoneNo;
      this.email = email;
      this.address = address;
   }
   public void displayContact() {
      System.out.println("Phone no: "+this.phoneNo);
      System.out.println("Email: "+this.email);
      System.out.println("Address: "+this.address);
   }
   protected Object clone() throws CloneNotSupportedException{
      return super.clone();
   }
}
public class StudentData implements Cloneable {
   private String name;
   private int age;
   private Contact contact;
   public StudentData(String name, int age, Contact contact){
      this.name = name;
      this.age = age;
      this.contact = contact;
   }
   public void displayData(){
      System.out.println("Name : "+this.name);
      System.out.println("Age : "+this.age);
      contact.displayContact();
   }
   protected Object clone() throws CloneNotSupportedException{
      StudentData student = (StudentData) super.clone();
      student.contact = (Contact) contact.clone();
      return student;
   }
   public static void main(String[] args) throws CloneNotSupportedException {
      Scanner sc =new Scanner(System.in);
      System.out.println("Enter your name ");
      String name = sc.next();
      System.out.println("Enter your age ");
      int age = sc.nextInt();
      System.out.println("#############Contact details#############");
      System.out.println("Enter your phone number: ");
      long phoneNo = sc.nextLong();
      System.out.println("Enter your Email ID: ");
      String email = sc.next();
      System.out.println("Enter your address: ");
      String address = sc.next();
      System.out.println(" ");
      //Creating an object of the class
      StudentData std = new StudentData(name, age, new Contact(phoneNo, email, address));
      //Creating a clone of the above object
      StudentData copiedStd = (StudentData) std.clone();
      //Modifying the data of the contact object
      copiedStd.contact.setPhoneNo(000000000);
      copiedStd.contact.setEmail("XXXXXXXXXX");
      copiedStd.contact.setAddress("XXXXXXXXXX");
      System.out.println("Contents of the copied object::");
      copiedStd.displayData();
      System.out.println(" ");
      System.out.println("Contents of the original object::");
      std.displayData();
   }
}

Output

Enter your name
Krishna
Enter your age
20
#############Contact details#############
Enter your phone number:
9848022338
Enter your Email ID:
krishna_example@gmail.com
Enter your address:
Hyderabad

Contents of the copied object::
Name : Krishna
Age : 20
Phone no: 0
Email: XXXXXXXXXX
Address: XXXXXXXXXX

Contents of the original object::
Name : Krishna
Age : 20
Phone no: 9848022338
Email: krishna_example@gmail.com
Address: Hyderabad

Updated on: 30-Jul-2019

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements