Why is the clone () method stored in Object?

If the class is not Cloneable , an object of this class cannot be cloned. Then why is clone() stored in the Object class and not in the Cloneable interface?

+4
source share
2 answers

It was a design mistake in Java (yes, Java is not perfect!).

Better to avoid cloning in Java. For example, Josh Bloch points to effective Java, clause 11:

The Cloneable interface was intended as the mixin interface (clause 18) for objects that advertise that they allow cloning. Unfortunately, this cannot serve this purpose. Its main drawback is that it lacks the clone method and the method of cloning objects. You cannot, without resorting to reflection (point 53), call the cloning method on an object only because it implements Cloneable. Even a reflective call may fail because there is no guarantee that the object has an available clone. Despite this shortcoming and others, the object is in wide use, so it pays to understand this.

If you want your objects to be cloned, use the copy constructor or copy method.

+2
source
  • Cloneable is a token interface, acts as a user / developer attribute to find out if a class is clone.

  • clone () is stored in the Object class because in your implementation of clone () it is recommended to call super clone (), this can only happen if the superclass has a clone function, even if it is not marked as cloned (by implementing Cloneable), therefore saving the clone () function in an object makes sense.

  • clone () creates another instance of the class, which, as a constructor, must call a super method to create a full instance.

0
source

All Articles