Meaningless Drivel is fun!*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes shallow cloning and deep cloning Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "shallow cloning and deep cloning " Watch "shallow cloning and deep cloning " New topic
Author

shallow cloning and deep cloning

Aaron Raja
Ranch Hand

Joined: Jun 07, 2007
Posts: 206
What are shallow cloning and deep cloning of objects? what is the main difference between


Thanks, AR
SCWCD 5, SCJP 1.4, OCA (PL/SQL)
John Stone
Ranch Hand

Joined: May 04, 2007
Posts: 332
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

Joined: Jun 07, 2007
Posts: 206
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

Joined: May 04, 2007
Posts: 332
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

Joined: Oct 14, 2002
Posts: 8879
    
    5
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.


Spot false dilemmas now, ask me how!
(If you're not on the edge, you're taking up too much room.)
 
 
subject: shallow cloning and deep cloning