In: Computer Science
In JAVA, What is the difference between a shallow copy and a deep copy? Include a simple illustration of the difference.
1. Shallow Copy in Java;
==> When user use default implementation of clone method user get shallow copy of object means it create new instance(object) and copy all the field of object to that new instance and return it as object type we need to explicitly cast it back to our original object.
==> This is shallow copy of the object.
==> clone() method of the object class support shallow copy of the object.
==> The name shallow copy or shallow cloning in Java.
2. Deep Copy in Java
==> When user need own meaning of copy not to use default implementation user call it as deep copy, when user need deep copy of the object user need to implement according to our need.
==> For deep copy user need to ensure all the member class also implement the Cloneable interface and override the clone() method of the object class.
==> After that we override the
clone() method in all those classes even in the classes where we
have only primitive type members otherwise user would not be able
to call the protected clone() method of Object class on the
instances of those classes inside some other class
shallow copy | deep copy |
|
|
|
|
|
|
|
|
|
|
|
|