The Artima Developer Community
Sponsored Link

Legacy Java Answers Forum
January 2002



This page contains an archived post to the Java Answers Forum made prior to February 25, 2002. If you wish to participate in discussions, please visit the new Artima Forums.



Posted by Matt Gerrans on January 20, 2002 at 4:08 PM

> [snip]
> > To add a few thoughts on this part, the behaviour of clone() is entirely dependant on how the method is implemented. For example, if the class implementing clone() has an instance of another class, the member object's clone() method (if present at all)is not called by default. Unless an explicit call to clone() is made to the member object, both the clones refer to the same member object!
> [/snip]

> both the clone() ? both of which clone(), since your statement includes this phrase "unless an explicit call to clone() is made to the member object"? and both refer to which member object?

I think he means that if the class being cloned has references to other classes, those must also be properly cloned. If it is not done, then your cloned object will refer to the same object as the object from which it was cloned. For example, suppose you have the following (omitting many details that I leave to your fertile imagination):

class CheeseDog implements Cloneable
private Cheese cheeseFlavor;

CheeseDog( Cheese flavor )
cheeseFlavor = flavor;

Now, if you do a new CheeseDog( new Cheese("gouda") ); and another new CheeseDog( new Cheese("gouda") ); you have four unique objects, but if instead of the second new CheeseDog( new Cheese("gouda") ); you had done a clone(), you could possibly have only three objects, because the same Cheese object maybe be referred to by both. What Jay is saying (I think), is now you have to go check out the implementation of clone() for the CheeseDog object and make sure that it does what you are expecting -- that is, is it cloning all of its contained objects (and are they cloning theirs, etc.)? It just opens a can of worms.

Not only that, but you have to deal with the annoying checked exception that clone() may toss.

The goofy thing about the Cloneable interface (besides its spelling) is that it is empty and just enables clients to call clone() on your class. However, you are not really forced to override the clone() method and if you don't then you get the default clong() of Object (or some superclass that overrode it), which may likely be inadequate. Additionally, even if the class in question (CheeseDog is this example) has overridden clone(), you have the lingering questions (mentioned above) about the suitability of its implementation to your purposes. All of this ambiguity is avoided with new.


Sponsored Links

Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us