Shallow Copy vs Deep Copy

Shallow Copy
By default when we call clone() method, it create shallow(little deep) copy of the object.
It create the copy of the primitive fields but copy only the reference of non primitive fields.
Above example is the example of Shallow copy. In this example it creates only one Department object and when we call clone() method it creates a new reference which refer to same Department object having values “12” and “OLPS”. In this if we change in Department values of one object then it will be reflected in copy object as well. This is the disadvantage of Shallow copy, to overcome this Deep copy comes.

Deep Copy
In this we need to override our clone() object inside the child object.

Class Department
   String name;
   String id;
   public Department(String name, String id)
    { = name; = id;
   protected Object cone() throws CloneNotSupportedException

In this case it will create a new object of Department as well. Emp1 and emp2 will be independent.