Marker interface

An interface without any members declared in it is called as Marker interface. i.e.; no methods and no constants available in this interface. Marker interface is also called as tagged interface. Java has few built in Marker interfaces as below

  • java.lang.Cloneable
  • java.io.Serializable

We can define marker interfaces just like how Java soft implemented above. Syntax as below

public interface <<MarkerInterfaceName>>
{
//Leave this blank... No method and No constants
}

What is the purpose of marker interface?

Marker or tagged interface adds some special behavior to the classes. To be honestly, I would not say it's special behavior as this behavior has been handled by another developer. Let me give you an example.

You can clone a Java object using java.lang.Cloneable. If you would like to learn cloning concept, please click here to read my other post. As per the Java API specification, one should implement the marker interface java.lang.Cloneable in order to achieve the cloning functionality. If you're not doing so, CloneNotSupportedException will be raised. This has been implemented in the clone method as below

public Object clone() throws CloneNotSupportedException
{
if(this instanceof Cloneable)
{
//Logic to clone the object
}
else
{
throw new CloneNotSupportedException();
}
}

this instanceof Cloneable returns true if the calling (current) object implements java.lang.Cloneable. So, cloning functionality has been designed in such a way that it is achieved only when a class implements java.lang.Cloneable.

Similarly, java.io.Serializable interface has been designed to designate the serialization for the objects. If a class doesn't implement Serializable, it raises NotSerializableException when it attempts to be used in serialization.