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.
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.
Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.