• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Cloning Concept

 
L Goundalkar
Ranch Hand
Posts: 395
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all..
Can anyone please explain me the cloning of objects in java.
When i clone a object i get the same reference of the cloned object, by using clone() method.
I can also do it by simply using following line..
ob2 = ob1; // where ob2 and ob1 are of same type.
So whats the difference between the two.
Thanks.

------------------
L Goundalkar
lggoundalkar@hotmail.com
Sun Certified Programmer for Java 2 Platform
 
Wilfried LAURENT
Ranch Hand
Posts: 269
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You may find hints in this
thread.

W.
 
Cindy Glass
"The Hood"
Sheriff
Posts: 8521
posted 14 years ago
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A shallow clone creates another instance whose fields point to the same objects as the original

A deep clone not only makes a copy of the object, but copies of all of the objects that it's fields are pointing to.



You need to be familiar with which methods of the APIs that you are using do which type of cloning. Sun was very good about insuring that this was well documented.
 
Ken Huskerson
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This thread has been very helpful. I was wondering if someone could venture a real world example of when you would need to use clone() outside of UI elements (buttons, etc.).

Thank you,

kh
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, we use it when we have several modifications to make to a piece of state in an "atomic" fashion. That is, the modified state doesn't become visible to other classes until all the modification are complete. Further, if any modification fails, others must be "rolled-back".

Say you have an object representing the current state. That is visible to other classes. When we want to start a set of modifications, we clone that object. The other classes continue to see the original object. We do our modifications to the new clone. If all the modifications are successful, we replace the original object by the new clone, as the object visible to other classes. But if any modification fails, we discard the clone.

You have to take care about deep versus shallow copies here. The clone() method does a shallow copy by default. It may be necessary to override clone() to do a deep copy.
 
Amit Saini
Ranch Hand
Posts: 280
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
http://www.ideas2work.com/java-articles/Java-Clone-DeepClone.html

this example might be helpful in understanding shallow vs deep cloning.

Amit
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic