Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Marker Interfaces

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 the clone() defined?

Why should we implement Clonable i/f whenever clone() is used?

Well my question was, if clone() is a method of java.lang.Object class, why implement Clonable i/f to override clone().

Could somebody elaborate on this convention of java ?

Thanks in Advance

like image 459
Ramya Avatar asked Nov 08 '12 08:11

Ramya


1 Answers

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.

like image 140
EdC Avatar answered Sep 18 '22 18:09

EdC