Search code examples
javacloneable

Under what situation an object should not be Clonable?


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?


Solution

  • 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.