cloning in java

By | May 29, 2014

Cloning in java or difference between deep copy and shallow copy of an object is a common interview question.
We have written this article in such a way that either you will be asked something from this article or you will able to answer the question bcoz of the knowledge you gained from this article.Let’s start .

clone() is method present in java.lang.Object class, which is used to create copy of an Object in Java.So what’s the difference between a clone or copy and a reference .
With respect to cloning these three conditions will be true.

  1. x.clone() != x [true]
  2. x.clone().getClass() == x.getClass() [true]
  3. x.clone().equals(x) [true]

The first condition won’t be true in case of reference
For example

here y will be equal to x and will be pointing to same address.

Difference between Deep Copy and Shallow Copy in java

Shallow copying generally means copying only one level of an object, while deep copying generally means copying more than one level.

consider this class

Now a shallow copy ie :
cloningExample a;//initialise
cloningExample c=a.clone();

Note that in java if you want to create the clone of an object then the class should implement Clonable interface and must override clone() method .Other wise you will get an exception.If you want to use default behavior use super.clone (shallow copying)
here c is copy of a where both c ad a have a variable i.They are different variables.It means if intially c.i=2 and a.i=2 and now if WE do some operations on c.i like ++c.i c.i will now be equal to 3 but a.i will still be equal to 2.But both c.o and a.o will point to the same object it means modificaitions in c.o will be reflected in a.o.
The default implementation provided by java is Shallow copying.

Now consider this code

So as you can see when deep copying we have overriden the clone() method in such a way that both a.o and c.o will point to equal but different objects .

For more tutorials see our tutorials page

Leave a Reply

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