Marker Interface in Java

By | January 28, 2015

One of the “clean” features of the Java programming language is that it mandates a separation between interfaces(pure behavior) and classes (state and behavior). Interfaces are used in Java to specify the behavior of derived classes.

Marker interface in Java is the interface with no fields or methods or in simple word an empty interface. Marker Interfaces are implemented by the classes or their super classes in order to add some functionality. Some examples of marker interfaces in the Java API include:

- java.lang.Cloneable
– java.io.Serializable
– java.util.EventListener

Marker interfaces are also called “tag” interfaces since they tag all the derived classes into a category based on their purpose.For example, all classes that implement the Cloneable interface can be cloned (i.e., the clone() method can be called on them). The Java compiler checks to make sure that if the clone() method is called on a class and the class implements the Cloneable interface. For example, consider the following call to the clone() method on an object o:

SomeObject o = new SomeObject();
SomeObject ref = (SomeObject)(o.clone());

If the class SomeObject does not implement the interface Cloneable (and Cloneable is not implemented by any of the superclasses that SomeObject inherits from), the compiler will mark this line as an error. This is because the clone() method may only be called by objects of type “Cloneable.” Hence, even though Cloneable is an empty interface, it serves an important purpose.

A marker interface called Thread Safe can be used to communicate other developers that classes implementing this marker interface gives thread-safe guarantee and any modification should not violate that. Again Annotations are better choice @ThreadSafe looks lot better than implementing ThraedSafe marker interface.

In summary marker interface in Java is used to indicate something to compiler, JVM or any other tool but Annotation is better way of doing same thing.

 

Leave a Reply

Your email address will not be published. Required fields are marked *