Opossum Opossum - 2 months ago 17
Java Question

Why does Object define clone() at all?

Object.clone() only works if the Cloneable interface is implemented, otherwise it throws an exception. If Cloneable is implemented then Object.clone() basically performs a memory copy, as far as I understand.

So, why is clone() defined in Object at all? Wouldn't it make a lot more sense to transfer the clone() default implementation to the Cloneable interface and have Object not mention clone() at all?

The only difference to the current specification would be that, instead of a runtime exception, you would get a compile-time error when attempting to clone a non-Cloneable object. Which would make a lot more sense.

Am I missing something?

Answer

Wouldn't it make a lot more sense to transfer the clone() default implementation to the Cloneable interface

Several points:

  1. it is impossible to change this now due to the issues of backward compatibility;
  2. even without the above, clone() is a low-level native method and interfaces cannot declare default native methods;
  3. even if it weren't a native method, it would still need access to object state and that would be in direct conflict with the idea behind default methods, which is to provide convenience API that can be expressed purely in terms of other interface methods.

A fair amount of general reasoning can also be found in this answer.

Comments