Could somebody pls explain the contract of marker interfaces in java?
For Ex: If Clonable
is a Marker Interface with no fields/methods, then where is t
clone()
is defined in the java.lang.Object
class which all classes extend from, however it is protected
. This is actually a concrete method implementation that does a field by field clone of the object, but only if you've implemented the Cloneable
interface to indicate this is allowed.
In practice many people override the clone()
method so that they can make it public
and allow cloning from outside the class.
This whole pattern is quite unusual and not something you would usually replicate, I can't think of many other examples in the JVM where there is a paired marker interface and method. From Java 5 onwards it's better to use annotations for markers. e.g. the @XmlRootElement
used to mark a type as Jax-B serializable (post Java 5) vs the Serializable
interface (pre Java 5) used to indicate a class is binary serializable.