Search code examples
javacloneable

What is the reason for ever needing to clone an object in java?


I was reading Joshua Bloch's Effective Java. In there he talks about not using the Clonable interface. I'm a bit of a noob so my question is, whats a use-case for when cloning would be required in code? Could someone give a sticky example so I can grasp the concept?


Solution

  • A clone() interface provides a mechanism to create a "shallow" copy of an object. That is, by default, more memory would be allocated for the copy, and each part of the original would be copied into the copy. In contrast, a simple assignment of an object instance to a variable would result in an additional reference to the same object. While the cloned object is itself a true copy, its contained elements are by default references to the ones referred to from the original. If a true "deep" copy is needed, the clone() method would need to be specialized to create clones of its members as well.

    One possible use case for a clone() interface would be for implementing a version history of an object to allow a rollback to an older version of it. This could be used in transactional systems, like databases.

    Another use case would be for implementing copy-on-write, and this can be useful when the user of the object is only provided a read-only version of the object.

    * Description of clone corrected, with thanks and kudos to newacct.