Wednesday, 21 March 2012

Java interview questions: - What do you mean by 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.

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


Visit for more author’s blog on Java interview questions

No comments:

Post a Comment