Java Marker Interface
Marker interface is used as a tag to inform a message to the java compiler so that it can add special behaviour to the class implementing it. Java marker interface has no members in it.
Lets take the java.io.Serializable marker interface. It doesnot has any members defined it it. When a java class is to be serialized, you should intimate the java compiler in some way that there is a possibility of serializing this java class. In this scenario, marker interfaces are used. The java class which may be serialized has to implement the java.io.Serializable marker interface. In such way, we are intimating the java compiler.
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.
Is Runnable a marker interface?
First point, there is no reference or definition about marker interface from Java specification/api. This is yet another inconclusive debate. ‘Marker Interface’ is a term coined by (book / web) authors. Since we don’t have Java’s definition it is left to us to arrive at a decent definition. This is one popular question asked in java interview. My answer to the interviewer, there are better questions ask than this to ask.
“Runnable is not a marker interface”, you might say ‘run’ is used to start a method and this is a special instruction to the JVM. When you run a java class the java interpreter calls the ‘main’ method, because of this would you say every java class as “marker class”?
‘My’ definition for marker interface
“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”.
In the above definition “and they do not have any method declarations” is added because, till now all the marker interfaces provided by java do not have method declarations. I dont think, in future there will be any new marker interfaces added :-)
We cannot create marker interfaces, as you cannot instruct JVM to add special behavior to all classes implementing (directly) that special interface.
Java Marker Interface Examples
This Abstract and Interface tutorial was added on 29/05/2008.