Shallow Copy vs Deep Copy in Java

Connect with

Oracle Java
Shallow cloning (copy) and deep cloning (copy) is one of the most important question in core java, which is being asked in the interview.

By default, all Java objects inherit built-in clone() method from the top-most java.lang.Object class. The built-in clone() method creates a clone / copy of the original object as a shallow copy not deep copy.

Shallow Copy ( Cloning)

  • The original top-level object and all of its primitive members are duplicated.
  • Any lower-level objects that the top-level object contains are NOT duplicated.
  • Only references to these objects are copied, it means, both original and cloned object referring to the same copy of lower-level object.

Deep Copy ( Cloning)

  • The original top-level object and all of its primitive members are duplicated.
  • The original top-level object and all of its primitive members are duplicated.
  • Any lower-level objects that the top-level object contains are also duplicated.It means, both original and cloned object referring to two different lower-level objects.

Example of Shallow Copy


package com.mysoftkey.core;

/**
 * This class is used to demostrate for shallow cloning of object.
 * 
 * @author ranjeet jha
 *
 */
public class ShallowCloningDemo {

	public static void main(String[] args) {
		
		//Original Object
		Employee employee = new Employee("Ranjeet", "New Delhi");
		System.out.println("Original value : name: " + employee.getName() + " , city:  " +  employee.getAddress().getCity());
		
		//Clone as a shallow copy
		Employee clonedEmp = (Employee) employee.clone();
		System.out.println("Clone (before change): " +	clonedEmp.getName() + " - " +	clonedEmp.getAddress().getCity());
		
		//change the primitive member i.e. name of employee
		clonedEmp.setName("Anushka");
		
		//change the lower-level object i.e. city under the address object.
		clonedEmp.getAddress().setCity("Gurgaon");
		System.out.println("Cloned (after change): name: " +	clonedEmp.getName() + " , city:  " +	clonedEmp.getAddress().getCity());
		System.out.println(	"Original (after clone is modified): name:  " + employee.getName() + " , city: " + employee.getAddress().getCity());
		}


}

/**
 * This is domain object for Employee , which hold reference of Address.
 * 
 * @author ranjeet jha
 *
 */
class Employee implements Cloneable {
	
        // primitive  
        private String name;

	// Lower-level object
	private Address address;
	

	public Address getAddress() {
		return address;
	}

	public String getName() {
		return name;
	}

	public void setName(String s) {
		name = s;
	}

	public Employee(String name, String city) {
		this.name = name;
		this.address = new Address(city);
	}

	@Override
	public Object clone() {
		
		// shallow copy
		try {
			return super.clone();
		} catch (CloneNotSupportedException e) {
			return null;
		}
		
	}
}

/**
 * This is Address DTO ( Data Transfer object) which hold reference of Address.
 * 
 * @author ranjeet Jha
 *
 */
class Address {
	
	private String city;

	public String getCity() {
		return city;
	}

	public void setCity(String cityName) {
		city = cityName;
	}

	public Address(String cityName) {
		city = cityName;
	}
}


Output of Shallow Cloning

Original value : name: Ranjeet , city:  New Delhi
Clone (before change): Ranjeet - New Delhi
Cloned (after change): name: Anushka , city:  Gurgaon
Original (after clone is modified): name:  Ranjeet , city: Gurgaon

Example of Deep Copy

Whenever you required a deep copy, you need to implement it yourself. When the copied object contains some other object its references are copied recursively in deep copy.

package com.mysoftkey.core;

/**
 * This class is used to demonstrate for Deepcloning of object.
 * 
 * @author ranjeet jha
 *
 */
public class DeepCloningDemo {

	public static void main(String[] args) {
		
		//Original Object
		Employee employee = new Employee("Ranjeet", "New Delhi");
		System.out.println("Original value : name: " + employee.getName() + " , city:  " +  employee.getAddress().getCity());
		
		//Clone as a shallow copy
		Employee clonedEmp = (Employee) employee.clone();
		System.out.println("Cloned object before change: name: " +	clonedEmp.getName() + " , city:  " +	clonedEmp.getAddress().getCity());
		
		//change the primitive member i.e. name of employee
		clonedEmp.setName("Anushka");
		
		//change the lower-level object i.e. city under the address object.
		clonedEmp.getAddress().setCity("Gurgaon");
		System.out.println("Cloned object after change: name: " +	clonedEmp.getName() + " , city:  " +	clonedEmp.getAddress().getCity());
		System.out.println(	"Original object , after clone is modified : name:  " + employee.getName() + " , city: " + employee.getAddress().getCity());
		}


}

/**
 * This is domain object for Employee , which hold reference of Address.
 * 
 * @author ranjeet
 *
 */
class Employee implements Cloneable {
	
	// Lower-level object
	private Address address;
	private String name;

	public Address getAddress() {
		return address;
	}

	public String getName() {
		return name;
	}

	public void setName(String s) {
		name = s;
	}

	public Employee(String name, String city) {
		this.name = name;
		this.address = new Address(city);
	}

	@Override
	public Object clone() {
			
		// Deep copy
		Employee emp = new Employee(name, address.getCity());
		return emp;
	}
}

/**
 * This is Address DTO ( Data Transfer object) which hold reference of Address.
 * 
 * @author ranjeet jha
 *
 */
class Address {
	
	private String city;

	public String getCity() {
		return city;
	}

	public void setCity(String cityName) {
		city = cityName;
	}

	public Address(String cityName) {
		city = cityName;
	}
}

Output of Deep cloning

Original value : name: Ranjeet , city:  New Delhi
Cloned object before change: name: Ranjeet , city:  New Delhi
Cloned object after change: name: Anushka , city:  Gurgaon
Original object , after clone is modified : name:  Ranjeet , city: New Delhi

Why Cloning is Required?

I have opened this question as of now to think on this and comment /suggestion.

Reference




Connect with

1 thought on “Shallow Copy vs Deep Copy in Java

Leave a Reply

Your email address will not be published. Required fields are marked *