Saturday, March 24, 2012

Marker Interface


About Marker interface in Java :

Marker interface is an interface with no method declaration.(Interface with no method definition)
Serializable is a one of the commonly used marker interface in java.

Some of the commonly used Marker interfaces
             -  java.lang.Cloneable
             -  java.util.EventListener

According to Object Oriented point of view Interface means Some behavior. So ,If a class implement one interface, then that class becomes the instance of that interface. That means it implements that behavior.(This implementation generally through give codes to the  method declared in the interface).

"But Marker interfaces will not have any method declaration. (That means it will not have any behavior to Implement)"
Then what is the purpose of implementing this useless interface?
A class implements a marker interface JVM  will automatically understand that  some special behavior is going to be implemented by the object of that class. So JVM create one mark on that object. So internally we force that object to execute some behavior.
Example :
        clone()  : This method is in class Object. If a class implement the " Cloneable " interface then JVM internally understand that some job has to be done by the object of that class . So JVM expect clone() method  to execute.
So internally we force the clone() method to execute.

So  ,
1) If a class implement Cloneable   interface it will tell the JVM that object of this class can be cloned (by implementing the method clone)
2) If a class   implement Serializable  interface it will tell the JVM that non-transient variables of this object can be stored



Exception  : Marker interface can contain method declaration.
Marker interface may or may not have method declaration....
Runnable is a marker interface. But it is having a mthod run().