Override clone judiciously

The Cloneable interface was intended as a mixin interface for objects to advertise that they permit cloning. Unfortunately, it fails to service this purpose. Its primary flaw is that it lacks a clone method, and Object’s clone method is protected. You cannot, without resorting to reflection, invoke the clone method on a object merely because it implements Cloneable. Even a reflective invocation may fail, as there is no guarantee that the object has an accessible clone method.

Cloneable interface determines the behavior of Object protected clone implementation: if a class implements Cloneable, Object’s clone method returns a field-by-field copy of the object, otherwise it throws CloneNotSupportedException.

The general contract of clone method is weak

  • Creates and returns a copy of this object. The precise meaning of “copy” may depend on the class of the object. The general intent is that for any object x, the expression x.clone() != x will be true, and the expression x.clone().getClass() == x.getClass() will be true, but these are not absolute requirements. While it is typically the case x.clone.equals(x) will be true, this is not an absolute requirement. Copying an object will typically entail creating a new instance of its class, but it may require copying of internal data structure as well. No constructors are called.

If you override the clone method in a non final class, you should return an object obtained by invoking super.clone. If all of class;s super classes obey this rule, then invoking super.clone will eventually invoke Object’s clone method, creating an instance of the right class.

In practice a class that implements Cloneable is expected to provide a properly functioning public clone method. It is not, in general, possible to do so unless all of the class’s superclass provide a well-behaved clone implementation, whether public or protected.

PhoneNumber example:

@Override public PhoneNumber clone() {
  try {
    return (PhoneNumber) super.clone();
  } catch (CloneNotSupportedException e) {
    throw new AssertionError(); // Can't happen

Read more about cloning objects in java on Vojtech Ruzicka’s Programming Blog

Lasă un răspuns

Adresa ta de email nu va fi publicată. Câmpurile obligatorii sunt marcate cu *

Acest site folosește Akismet pentru a reduce spamul. Află cum sunt procesate datele comentariilor tale.