Reference copy , Shallow copy and Deep Copy
Before Getting Started we need to understand one basic thing about object in java. In java every object we create is a reference to actual object created in the heap.
Now , we are on same page. Let’s dig into details.
1. Reference Copy
When we assign one object to another object , then a reference copy is generated and the newly assigned object is just another reference to the previous “Actual Object” created.
When we change any data member from one object , changes are reflected back in another object.
Output of this program is :
As you can see, any changed in model object is also reflected back into referenceCopy object.
Before proceeding further you need to understand one more thing. Cloneable interface in java is a marker interface to create clone (shallow copy & deep copy) of object. As it is a marker interface that means it doesn't have method to implement. It just say “this class is clonable”.
2. Shallow copy
Shallow copy is a bit-by-bit copy of the object. All the data member and reference are copied and assigned to new object. So, unlike reference copy, newly created object point to its own “Actual object” . However , in shallow copy reference are also copied i.e, the all the reference object inside object still point to the same object as the original object.
What i meant by it?
In the above diagram, we have two object. Let’s assume , right object is shallow copy of left object.
- As shallow copy, both object points to different object in memory.
- Each object has it’s own copy of non-reference data member ( age,name)
- Shallow copy , don’t create copy of reference object , hence we have only one address object referred by both the object.
Implementation.
Shallow copy is created using clone method present in object class. Default implementation only create shallow copy.
Output:
From the output we can see that any changed in non-reference(mobile No) data member is independent while address object is changed when we change one object.
3. Deep Copy
Deep copy replicate all the data member along with all the reference object recursively. So, new object is also created for reference. This process is recursive i.e, if reference object contain other reference , new object are also created for them.
Object are also created for address object.
Implementation:
Deep copy is similar to shallow copy implementation. Only difference is in clone method.
We create a new object of usermodel as well as address object. Note that, addressmodel is also clonable, otherwise it will throw CloneNotSupportedException.