Why wasn't the .clone()
method specified in the java.lang.Cloneable
interface ?
The Java. There is a method clone() in the Object class. Cloneable interface is implemented by a class to make Object. clone() method valid thereby making field-for-field copy. This interface allows the implementing class to have its objects to be cloned instead of using a new operator.
Object's clone() method probably just checks it using: this instanceof Cloneable. The reason that the clone() method is defined in the Object class, is because some 'magic' is needed to actually make a clone. First of all, a new object has to be created without the use of a constructor.
A marker interface is an interface that has no methods or constants inside it. It provides run-time type information about objects, so the compiler and JVM have additional information about the object. A marker interface is also called a tagging interface.
Examples of marker interface are Serializable, Cloneable and Remote interface. All these interfaces are empty interfaces. Examples of Marker Interface which are used in real-time applications : Cloneable interface : Cloneable interface is present in java.
Basically, it's a broken interface. Ken Arnold and Bill Venners discussed it in Java Design Issues.
Arnold:
If I were to be God at this point, and many people are probably glad I am not, I would say deprecate
Cloneable
and have aCopyable
, becauseCloneable
has problems. Besides the fact that it's misspelled,Cloneable
doesn't contain theclone
method. That means you can't test if something is an instance ofCloneable
, cast it toCloneable
, and invokeclone
. You have to use reflection again, which is awful. That is only one problem, but one I'd certainly solve.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With