This week's book giveaway is in the Performance forum.
We're giving away four copies of The Java Performance Companion and have Charlie Hunt, Monica Beckwith, Poonam Parhar, & Bengt Rutisson on-line!
See this thread for details.
Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

shallow cloning and deep cloning

 
Aaron Raja
Ranch Hand
Posts: 206
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What are shallow cloning and deep cloning of objects? what is the main difference between
 
John Stone
Ranch Hand
Posts: 332
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can imagine shallow cloning as applying assignment operator on each non-static attribute member of your class.



myNewObject.[attribute] = originalObject.[attribute]

Now, let's say that this attribute was reference to object of type "Dog". So your new object will have copy of this reference, which will point to object of type "Dog", but it will be the same Dog instance. Cloning owner will not create new Dog instance.

Deep copy ensures, that every referenced object will be cloned as well. So cloning owner in this case would create a new dog for him and you would have 2 owners and 2 dogs.
 
Aaron Raja
Ranch Hand
Posts: 206
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I understand book defination
If a shallow copy is performed on obj-1 then it is copied but its contained objects are not. The contained objects Obj-1 and Obj-2 are affected by changes to cloned Obj-2. Java supports shallow cloning of objects by default when a class implements the java.lang.Cloneable interface.
If a deep copy is performed on obj-1 then not only obj-1 has been copied but the objects contained within it have been copied as well. Serialization can be used to achieve deep cloning. Deep cloning through serialization is faster to develop and easier to maintain but carries a performance overhead.

I need more real life example if you can think of? and senerio where to use it.
 
John Stone
Ranch Hand
Posts: 332
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
deep:

Clone of this Car should have its own wheels.

shallow:

Clone of twin (his brother or sister) should have same mother.


It depends on situation and what are you trying to accomplish.
 
Bert Bates
author
Sheriff
Posts: 8898
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just remember that this topic isn't in the 1.4 exam at all, and in the 5.0 exam this relates only to Serialization.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic