Override clone judiciously in java

This is a piece of advice from Joshua Bloch on Effective Java book.

In practice, a class that implements Cloneable is expected to provide a properly functioning public clone method. In effect, the clone method functions as another constructor; you must ensure that it does no harm to the original object and that it properly establishes invariants on the clone. The clone architecture is incompatible with the normal use of final fields referring to mutable objects. A fine approach to object copying is to provide a copy constructor or copy factory.

Special notes

  • When we implement Cloneable, we should also override the clone with a public method whose return type is the class itself. This method should start by calling super.clone and then clone all the mutable objects of the class.
  • When we need to provide a way to copy classes, we can think of copy constructor or copy factory except for arrays.
  • In order to make a class cloneable, it may be necessary to remove final modifiers from some fields.
  • It doesn’t make sense for immutable classes to support object copying, because copies would be virtually indistinguishable from the original.
  • Java also supports copy constructor. Java doesn’t create a default copy constructor unless we write our own.
  • New extendable class should not implement Cloneable