Pages

Tuesday 14 January 2014

What is Null interface or Marker Interface in Java?

What is Null interface or Marker Interface in Java?

Marker Interfaces are those which doesn't contain any methods, but which got some purpose or capability.

It gives a message to the java compiler that it can add some special behaviour towards the class which implementing it.

Some of the Marker Interfaces are:
  • java.lang.Cloneable
  • java.io.Serializable
  • java.util.EventListener

Let's take an example:

1) java.io.Serializable 

java.io.Serializable is a marker interface, it doesn't contain any method declarations.

When a java class is to be serialized , i.e when we want to store the state of an object or pass through the network, we should intimate the java compiler in some way that there is a possibility of serializing this java class.

The java class which needs to be serialized has to implement the java.io.Serializable marker interface and by doing this we are informing the java compiler to add that capability.

2) java.lang.Cloneable

All classes that implement the Cloneable interface can be cloned (i.e., the clone() method can be called on them). 

The Java compiler makes sure that if the clone() method has been called on that class which implements Cloneable Interface and also the class is implementing the Cloneable interface.

For example, consider the following call to the clone() method on an object cloneableClass:

CloneableClass cloneableClass = new CloneableClass ();
CloneableClass cl = (CloneableClass )(cloneableClass.clone());

In the above, the CloneableClass should implement the interface Cloneable, if not then the compiler will give an error. This is because the clone() method may only be called by objects of type "Cloneable."

So even if, Marker Interfaces are empty one's, it holds some special purpose.