Thursday, July 19, 2012

Marker or Tag interface in java


An interface is called a marker interface when it is provided as a handle by java interpreter to mark a class so that it can provide special behaviour to it at runtime and they do not have any method declarations.

Java Marker Interface Examples


  • java.lang.Cloneable
  • java.io.Serializable
  • java.util.EventListener

Why we need Marker Interface?

Suppose you want to persist (save) the state of an object then you have to implement the Serializable interface otherwise the compiler will throw an error. To make more clearly understand the concept of marker interface you should go through one more example.
Suppose the interface Clonable is neither implemented by a class named Myclass nor it’s any super class, then a call to the method clone() on Myclass’s object will give an error. This means, to add this functionality one should implement the Clonable interface. While the Clonable is an empty interface but it provides an important functionality.
We cannot create marker interfaces, as you cannot instruct JVM to add special behavior to all classes implementing (directly) that special interface.
From java 1.5, the need for marker interface is eliminated by the introduction of the java annotation feature. So, it is wise to use java annotations than the marker interface. It has more feature and advantages than the java marker interface.

No comments: