Cloning is a process of creating a replica or copy of java object, clone method Java.lang.Object is used to create copy or replica of an object. java objects which implement Cloneable interface are eligible for using the clone method. In this article, we will discuss the Shallow Copy and Deep Copy in the following order:
- Creating Copy of Java Object
- What is a Shallow Copy?
- What is a Deep Copy?
- Difference Between Shallow Copy and Deep Copy
Creating Copy of Java Object
We can create a replica or copy of java object by
1. Creating a copy of object in a different memory location. This is called a Deep copy.
2. Creating a new reference that points to the same memory location. This is also called a Shallow copy.
Shallow Copy
The default implementation of the clone method creates a shallow copy of the source object, it means a new instance of type Object is created, it copies all the fields to a new instance and returns a new object of type ‘Object’. This Object explicitly needs to be typecast in object type of source object.
This object will have an exact copy of all the fields of source object including the primitive type and object references. If the source object contains any references to other objects in field then in the new instance will have only references to those objects, a copy of those objects is not created. This means if we make changes in shallow copy then changes will get reflected in the source object. Both instances are not independent.
The clone method in Object class is protected in nature, so not all classes can use the clone() method. You need to implement Cloneable interface and override the clone method. If the Cloneable interface is not implemented then you will get CloneNotSupportedException.super.clone () will return shallow copy as per implementation in Object class.
Code for Shallow Copy
package com.test; class Department { String empId; String grade; String designation; public Department(String empId, String grade, String designation) { this.empId = empId; this.grade = grade; this.designation = designation; } } class Employee implements Cloneable { int id; String name; Department dept; public Employee(int id, String name, Department dept) { this.id = id; this.name = name; this.dept = dept; } // Default version of clone() method. It creates shallow copy of an object. protected Object clone() throws CloneNotSupportedException { return super.clone(); } } public class ShallowCopyInJava { public static void main(String[] args) { Department dept1 = new Department ("1", "A", "AVP"); Employee emp1 = new Employee (111, "John", dept1); Employee emp2 = null; try { // Creating a clone of emp1 and assigning it to emp2 emp2 = (Employee) emp1.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } // Printing the designation of 'emp1' System.out.println(emp1.dept.designation); // Output : AVP // Changing the designation of 'emp2' emp2.dept.designation = "Director"; // This change will be reflected in original Employee 'emp1' System.out.println(emp1.dept.designation); // Output : Director } }
Output:
In the above example, we have an Employee class emp1 which has three class variable id (int), name (String ) and department (Department).
We now cloned emp1 to emp2 to create a shallow copy, after that we changed designation using emp2 object and verified that the same changes got reflected in emp1 also.
Deep Copy
The deep copy of an object will have an exact copy of all the fields of source object like a shallow copy, but unlike sallow copy if the source object has any reference to object as fields, then a replica of the object is created by calling clone method. This means that both source and destination objects are independent of each other. Any change made in the cloned object will not impact the source object.
Code for Deep Copy
package com.test; class Department implements Cloneable{ String empId; String grade; String designation; public Department(String empId, String grade, String designation) { this.empId = empId; this.grade = grade; this.designation = designation; } //Default version of clone() method. protected Object clone() throws CloneNotSupportedException { return super.clone(); } } class Employee implements Cloneable { int id; String name; Department dept; public Employee(int id, String name, Department dept) { this.id = id; this.name = name; this.dept = dept; } // Overriding clone() method to create a deep copy of an object. protected Object clone() throws CloneNotSupportedException { Employee emp = (Employee) super.clone(); emp.dept = (Department) dept.clone(); return emp; } } public class DeepCopyInJava { public static void main(String[] args) { Department dept1 = new Department("1", "A", "AVP"); Employee emp1 = new Employee(111, "John", dept1); Employee emp2 = null; try { // Creating a clone of emp1 and assigning it to emp2 emp2 = (Employee) emp1.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } // Printing the designation of 'emp1' System.out.println(emp1.dept.designation); // Output : AVP // Changing the designation of 'emp2' emp2.dept.designation = "Director"; // This change will be reflected in original Employee 'emp1' System.out.println(emp1.dept.designation); // Output : AVP } }
Output:
In the above example of Deep copy, unlike shallow copy, both source and destination objects are independent of each other. Any change made in emp2 will not impact emp1.
Difference Between Shallow Copy and Deep Copy
Shallow Copy | Deep Copy |
Cloned object and source object are not disjoint completely | Cloned objects and source objects are completely independent of each other. |
Changes made in the cloned instance will impact the reference variable of the source object | Changes made in the cloned instance will not impact the reference variable of the source object. |
The default version of the clone is the shallow copy | To create deep copy we need to override the clone method of Object class. |
Shallow copy is preferred if class variables of the object are only primitive type as fields | A deep copy is preferred if the object’s class variables have references to other objects as fields. |
It is relatively fast | It is relatively slow. |
With this, we come to the end of Shallow Copy and Deep Copy article. I hope you got an understanding of the various differences between the two.
Check out the Java Course training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. Edureka’s Java J2EE and SOA training and certification course is designed for students and professionals who want to be a Java Developer.
Stay up-to-date with the latest Flutter features and best practices through our Flutter Course.
Got a question for us? Please mention it in the comments section of this “Shallow Copy and Deep Copy” blog and we will get back to you as soon as possible.