2

The basic collection interfaces (List, Map, Set) do not extend Cloneable interface. This is done in order NOT to enforce Cloneability for concrete implementations.

All of the collection classes do implement Cloneable interface so they all are inherently Cloneable. Also Cloneable is a marker interface meaning it signals the compiler/JVM to do some additional work behind the curtain, so as make that object Cloneable.

Now my question is : What the situations where in you DO NOT want your object to be Cloneable?

Santosh
  • 17,667
  • 4
  • 54
  • 79
  • The List, Map, Set extend Collection don'T they? So they implement clonable anyway – Matthias Bruns Dec 14 '11 at 05:54
  • Nevermind, just checked the Collection-Framework - it does not implement Cloneable – Matthias Bruns Dec 14 '11 at 05:56
  • I don't think a marker interface is a signal to do anything magical behind the scenes. It simply means that `instanceof Cloneable` will return `true`. (This is not to say that there isn't magic going on in calls to `clone()`; just a comment about the term "marker interface".) – Ted Hopp Dec 14 '11 at 05:57
  • I don't think a marker interface is a signal to do anything magical behind the scenes. It simply means that `instanceof Cloneable` will return `true`. (This is not to say that there isn't magic going on in calls to `clone()`; just a comment about the term "marker interface".) – Ted Hopp Dec 14 '11 at 05:57

4 Answers4

3

Singleton is a good case. Another is anything where you have a reference to something on the system that you should only have ONE reference to. For example, a Stream. Having multiple objects point to the same input (or output) stream could cause all kinds of problems.

If you want to use clone(), consider creating a copy constructor instead.

Bob Gilmore
  • 12,608
  • 13
  • 46
  • 53
2

If your class holds a huge chunk of data then you may not want it to be cloned to stop keeping multiple copy of a big chunk of data.

anubhava
  • 761,203
  • 64
  • 569
  • 643
  • I might need this in case I want to keep class holding huge chunk of data immutable and use its copy/clone whenever needed elsewhere. Just like strings. – Santosh Dec 14 '11 at 06:56
1

If you were to implement the Singleton pattern, you probably wouldn't want the resulting Singleton to be cloneable.

Todd
  • 30,472
  • 11
  • 81
  • 89
1

I wouldn't want to have cloneable threads :X Neither cloneable resource classes or session beans

Matthias Bruns
  • 899
  • 8
  • 13