Java interview questions: – How will you explain the fundamentals of deep and shallow Cloning?

This is the most practical oriented Java Interview Questions which may be asked during the Interview by the Interviewer.

Many times in project you need to create exact copy of the object and operate on them. To do this there two ways of doing it Shallow clone and Deep clone. When an object is Shallow cloned the parent object or the top level object and its members are duplicated. But any lower level objects are not duplicated. Rather references of these objects are copied. So when an object is shallow cloned and you modify any of it child classes it will affect the original copy. When an object is deep cloned the entire object and its aggregated objects are also duplicated.

Below is the diagram which explains things in a clear and pictorial manner.

cloning

Figure: – Deep clone and Shallow clone in action

In the above diagram there are three blocks the first block is the original object, second block is the Shallow clone and the third is Deep clone block. Here the object to be cloned is a simple Customer class which has multiple addresses. Now when you shallow clone it you can see the top class clsCustomer is duplicated but clsAddresses still refers to the original object. But in case of Deep clone complete new copy is created of the whole structure.

See the following video on Java which describes Value List Handler: –


Click for more Java interview questions

Regards,

Visit for more author’s blog on Java interview questions

Advertisements

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