Search code examples
javainterfaceclonecloneable

Why shouldn't an object be cloneable?


I read lots of threads about the clone() method of Object and the Cloneable Interface but I couldn't find a legitimate answer to my question. Long story short:

What I figured out is that Object has a method clone() which can "magically" clone your object. But you can't use that method without implementing Cloneable Interface because this interface allows Object to use the clone() method. So why did they do that? Why shouldn't every object be cloneable from the start?


Solution

  • Cloneable makes sense for some mutable data.

    It doesn't make sense for

    • immutable data
    • where you might need a shallow or a deep copy.
    • objects which represent resources such as threads, sockets, GUI components
    • singleton and enumerated types
    • mutable state where data should only be copied to avoid creating new objects.

    Some coding styles suggest keeping new mutable data object to a minimum. Cloneable doesn't suit all situations and if you made all objects Cloneable you wouldn't be able to turn it off cleanly.

    Note: There are many projects which avoid using Cloneable anywhere.