SHALLOW AND DEEP COPY

Shallow Copy

  • When a object is copied then it primitive variables and reference variables are also copied.
  • Assume we have Class A which has a int i and Class B reference
  • After copying the new object will have a copy of int i and  it will pointing to the same reference of class B that is referred in Class A
  • Hence Copied Object will point to the same Class B reference as that of Class A.
  • This will enable both Class A and Copied object to have the same copy of Class B instead of independent copy.
  • Used when the Objects contains only primitive variables
  • Or When the referenced Objects going to remain unchanged.
  • Object Class clone() method by default supports Shallow Copy
  • Need to implement Cloneable Interface (Marker Interface – Methodless)
  • Should Overwrite clone() method and call super.clone() for shallow copy as clone() is a protected method.

Deep Copy

  • When a object is copied then it primitive variables and reference variable’s Object is  also copied.
  • Assume we have Class A which has a int i and Class B reference
  • After copying the new object will have a copy of int i and a copy of Class B
  • This will enable both Class A and Copied object to have the independent copy of  Class B
  • Used when the objects references many other objects which tend to change frequently
  • Need to implements a logic in the clone method to recursively copy all objects referred in the class
  • Avoid landing into cyclic dependencies (???)
  • Alternative for Deep Copy – Serialization.
  • Serialization – default  implements Deep copy and handles Cyclic dependencies
  • Does not handle final. Hence implementation should take care of handling them during cloning.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Cheat Sheet To JAVA Latest Technology

%d bloggers like this: