What is a marker interface
An interface which has no methods is called a marker interface in java.
In other words, it is an empty interface having no method declarations or constants.
There is no term as marker interface in the official java docs. The source of this term is not known.

Marker interface in java library
Following are the interfaces in java api that do not have any method declarations nor any constant, they are empty.
They are a signal to the compiler to ensure that only the objects implementing them are allowed to perform a specific operation.

  • java.io.Serializable: Objects which need to be saved to a file should implement this interface.
    If an attempt is made to serialize an object that does not implement this interface, then java.io.NotSerializableException is thrown.
  • java.rmi.Remote: Objects whose methods may be invoked remotely should implement this interface.
    If a remote object does not implement this interface, then a java.rmi.RemoteException is thrown.
  • java.lang.Cloneable: If you want to make a copy of an object or clone an object in java, then its class should implement this interface.
    Attempting to clone an object which does not implement this interface will result in a java.lang.CloneNotSupportedException.

From the above discussion, you can sense that even though these interfaces do not contain any method, still if they are not implemented, then the desired operation(such as cloning) will fail.

Thus, inside the implementation of native clone() method, there would be a check that confirms that the object being cloned implements java.lang.Cloneable interface such as

if(!object instanceof Cloneable) {
   throw new CloneNotSupportedException();

and similarly for serialization process

if(!object instanceof Serializable) {
   throw new NotSerializableException();

Use of marker interface in java
Marker interface is used to tell the java runtime that objects of the class that implement this interface should be allowed to perform some operation such as serialization or call a remote method.
Thus, if you want only selective objects to be able to qualify for some task, then create a marker interface and make the class of those objects implement it.

Marker interface will provide a check at execution time that only valid objects should take some action otherwise an error should be thrown, as we saw above.
This will be more clear after we look at creating our own marker interface example covered next.
Creating own custom marker interface
It is possible to create a user defined marker interface in java. Create an empty interface without any methods or constants in it.
Suppose we do not want all objects to be updated and only some objects specifying a certain criteria should be allowed to update.

This can be achieved using a marker interface as shown ahead.

public interface Updatable{

Here we create our own interface Updatable which does not contain any methods.
We want to ensure that only those objects which implement this interface should be allowed to be updated.
So, in the method which performs update operation of objects, we can put a check as below.

public void update(Employee emp) {
   if(!emp instanceof Updatable) {
      throw new Exception("Update operation not allowed for this object");
   // update employee

Now only those objects which implement Updatable or are of the type Updatable will be allowed to be updated.
All other objects will only be in read-only state.

Marker interface vs annotations
Java 5 introduced the concept of annotations which can be applied over a field, method or class.
They can be used to achieve the same result as marker interfaces.
Annotations can be used to provide information regarding the class or method where it is applied and to take or prevent some action at execution time.

For example, we can apply an annotation at the class and during execution we can check if the object of this class has an this annotation.
If the annotation is present, then allow some operation else deny it(similar to the custom marker interface example shown above).

Besides using the built-in annotations of java library, it is also possible to create custom annotations.
Now the following questions arise,

  • What should be preferred, annotations or marker interfaces?
  • Are marker interfaces now obsolete?

Following discussion will try to throw some light on this comparison.
1. Annotations can only be checked at run time using reflection, which is an expensive or performance intensive operation.
There is no way to check the presence of annotation on a method or class at compile time.
For confirming if an object has an annotation applied over its class, one would require following piece of code.

public void update(Employee emp) { 
  // check for @Update annotation  
  if (!emp.getClass().isAnnotationPresent(Update.class)) {        
    throw new Exception("cannot perform action...");    
  // perform update operation

Now one may state that marker interfaces are also checked at execution time, which is right but instanceof operator check for marker interface is not as expensive as reflection for annotations.

Secondly, with marker interfaces, it is possible to check at compile time and avoid the runtime check altogether using Polymorphism as shown ahead.
Modify the update method code from last section to:

public void update(Updatable emp) {
   * No Need Of This
   * if(!emp instanceof Updatable) { 
   *   throw new Exception(
   *          "Update operation not allowed for this object"); 
   * }
   // directly update employee

Notice that the update method now takes an object of Updatable, which is the interface type and not the implementing class type.

Now, you can only supply objects which implement Updatable to this method otherwise a compiler error will be raised, thus avoiding the need for any runtime check.
This can not be done using annotations.
2. If a class implements a marker interface, then all of its child classes also implement it by default which means that there is no method by which you can allow an operation for child objects while restricting it for parent objects.

Example, suppose a class Manager extends Employee. Now since Employee implements Updatable, Manager also implements it.
Now it is required that Employee objects should be permitted update operation while Manager should not, then this can not be done with the below condition

if(! emp instanceof Updatable) {
   throw new Exception(
          "Update operation not allowed for this object");
// update object

since Manager objects are also instances of Updatable and they will not be stopped from updating.
While, this is possible with annotations since an annotation can be applied at class level and is not inherited.
Thus, if @Updatable annotation is applied to Employee, then it is not applicable for objects of Manager.
Marker Interfaces vs Interfaces
Marker interfaces differ from regular interfaces in that they contain no method or constant unlike normal interfaces.
Thus, if a class implements a marker interface, it does not need to add any method definitions.
But you cannot use a marker interface in place of a regular interface since it has no behavior(methods represent behavior).
Also, it violates the contract between a class and an interface that when a class implements an interface, it also needs to implement methods of that interface.
Hope this post was useful for you to understand the concept of marker interfaces and their purpose in java.
Hit the clap below if you liked it.

Liked the article ? Spread the word...

Leave a Reply