Shallow Cloning and Deep Cloning

When we create a clone of an object we allocate a new memory location and copy the content of the cloned object to the new location. The cloning of objects can happen in two possible ways: shallow cloning and deep cloning.

When we clone any object using Object.clone() method, we actually create a shallow copy of the object, thus we use shallow cloning.


Shallow Cloning

This is the way of cloning where a new instance of the same class is created and all the primitive types are copied to the new instance from the object to be cloned. If the object to be cloned has non-primitive types, only the object references will be copied, not the original object. That’s the reason why this way of cloning an object is called as shallow cloning.

shallow-cloning

Note: New copies of immutable object will be created in the cloned object as well. Hence if the object cloned has only primitive types and/ or immutable objects, there would be no difference between deep copy and shallow copy.


Deep Cloning

In deep cloning, a new instance of the same classes is created by copying the primitive types as well as the non-primitive types, from the object to be cloned. In deep cloning a copy of all non-primitive types is also created.

shallow-cloning

We cannot reply on the Object.clone() method if we want a deep copy of any object. We will have to provide our own implementation for deep cloning the object.

One way to produce a deep clone of an object is by using serialization. Since in serialization, we serialize the state of an entire object graph, serializing and deserializing an object can produce a deep copy of the object. Shown below is a sample code to deep copy an object using serialization:

public Employee deepCopy(Employee emp) throws IOException {
     ObjectOutputStream outputStream = null;
     ObjectInputStream inputStream = null;
     try {
         ByteArrayOutputStream bos =  new ByteArrayOutputStream(); 
         outputStream = new ObjectOutputStream(bos); 
         outputStream.writeObject(emp);   
         outputStream.flush(); 
         
         inputStream = new ObjectInputStream(
                   new ByteArrayInputStream(bos.toByteArray()));                  
         return (Employee)inputStream.readObject(); 
      }
      catch(ClassNotFoundException e) {
         return null;
      }
      finally {
          outputStream.close();
          inputStream.close();
      }
}

Note: Deep Cloning is a very complex implementation. To produce a deep copy of an object, we should use a third-party library like apache-common-langs, rather than implementing our own code.

RELATED ARTICLES

2 ways to Create a Thread in Java

Threads in Java can be created in 2 different ways, extending the Thread class and implementing the Runnable interface. This article explains the two ways with suitable examples.

View Article

4 Different Ways of Creating an Object in Java

Most of us have created object using new operator in Java. Did you know the other ways to create objects in Java. This article talks about 4 different ways of creating objects in Java.

View Article

Using AutoCloseable with 'try-with-resources'

Java 7 added the java.lang.AutoCloseable interface that developers can implement in their custom classes for using them with try-with-resources.

View Article

Chained Exception

Chained exception is a feature introduced with JDK 1.4, which allow developers to associate an exception with another exception.

View Article

Exception Handling in Inheritance

There are certain rules that must be followed while throwing exceptions in inheritance and overriding methods. This article discuss about these rules.

View Article

Garbage Collection in Java

Java Garbage Collector is a boon to Java developers; it allows developers to program without worrying about memory management. This article describes the working of Java Garbage Collector in details.

View Article

Understanding static and final in Java

Java provides various modifiers which when used with variables, methods or classes, provides them with special properties. Static and final are are two such modifiers which are used frequently by Ja..

View Article

Understanding Object Cloning

Java provides the clone() method which can be used to create a copy an object. It creates a new memory location and copies the content of the object being cloned into the new location.

View Article

Try-with-resources Statement in Java 7

Java 7 introduces the new 'try-with-resources' statement which help developers to overcome the tedious task of closing the resources that have been used in the program.

View Article

Varargs: Variable Arguments to Methods

Java 5 introduced a new feature called varargs, which allows methods to accept variable number of arguments. They are useful in cases where the number of arguments to be passed to a method is unknown.

View Article