When you do a clone of an Object 'A'
, you are creating a new Object 'B'
(with the same references to objects) but in a different memory address. Thus, when you modify the object 'A' you are not accessing the same memory address of the Object 'B'
. Therefore, changes in the clone do not reflect back in the original object and vice-versa.
Shallow Copy
Generally, the clone method of an object, creates a new instance of the same class and copies all the fields to the new instance and returns it. This is nothing but shallow copy. Object class provides a clone method and provides support for the shallow copy. It returns ‘Object’ as the type and you need to explicitly cast back to your original object.
Deep Copy
When you need a deep copy then you need to implement it yourself. When the copied object contains some other object its references are copied recursively in the deep copy. When you implement a deep copy be careful as you might fall for cyclic dependencies. If you don’t want to implement deep copy yourself then you can go for serialization. It does implement deep copy implicitly and gracefully handling cyclic dependencies.
(source about the information)
Here an illustrative example:
Shallow
Deep:
(source: wikimedia.org)