Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Rationale of the Cloneable interface

Why wasn't the .clone() method specified in the java.lang.Cloneable interface ?

like image 756
Ande Turner Avatar asked Apr 02 '09 11:04

Ande Turner


People also ask

Why do we use cloneable interface in Java?

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.

Why should we implement cloneable interface if we have to clone an object though clone method comes from object class?

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.

Why do we use marker interface in Java?

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.

Is cloneable marker interface in Java?

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.


1 Answers

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 a Copyable, because Cloneable has problems. Besides the fact that it's misspelled, Cloneable doesn't contain the clone method. That means you can't test if something is an instance of Cloneable, cast it to Cloneable, and invoke clone. You have to use reflection again, which is awful. That is only one problem, but one I'd certainly solve.

like image 151
Bill the Lizard Avatar answered Sep 19 '22 11:09

Bill the Lizard