tags:

views:

104

answers:

2

I have never seen clone() method put to use in any real code. I was reading about it and felt that its use could make the code very cumbersome. is there any specific use case for the clone() method? Under what circumstances would one have to use clone() and why would the use normal conctructor not suffice?

+2  A: 

Josh Bloch in Effective Java also doesn't recommend to use clone () method.

There are several problems with this method:

1) If cloneable object have not only primitive type fields but also object fields then cloned object will receive just references to those objects but not real cloned objects. To avoid this all inner objects should be cloneable too.

2) If you make a subclass of cloneable class then it's cloneable too (even if you don't want). That's why you should override clone () method in a proper way to avoid possible problems.

When you should use it: never if possible. You should use it very carefully. If all fields in object you want to make cloneable are of primitive type then it's not dangerous. In all other cases think twice before using it.

Roman
hmm...that is the book i am reading currently..everything about the method looks dirty...was wondering why it exists at all
Aadith
First version of java was released rather fast. They made great work and numerous their decisions were very smart. But they also made a few mistakes, like java.util.Date class or clone () method. If it was added once to the API they can't ever change it.
Roman
@Roman what about java.util.Date? why was it a mistake?
Aadith
At the moment java.util.Date is implemented in that way that everyone should look for 3rd-party libraries like Joda Time. There are lots of weak places in Date now. You can google a comparison of Joda Time and Dates in java. But java team promises that they fix all problems and make dates almost like in Joda Time in Java 7.
Roman
Nothing prevents you from overriding clone() to perform a deep copy.
MSN
Sometimes we use classes from 3rd-party libraries which don't implement cloneable.
Roman
+2  A: 

clone is very convenient to make defensive copies of arrays passed to methods or constructors (as all array types are Cloneable, and the signature for clone()is covariant so that boolean[].clone() actually returns a boolean[] rather than an Object). That's the only really good use I've seen of it in ten years, though...

gustafc