Showing posts with label Tag Interface. Show all posts
Showing posts with label Tag Interface. Show all posts

What is Marker Interface in Java?

Marker interfaces are special interfaces in Java. Marker interface will not have any methods or member variables. Just declared with interface name and also called as Tag interface. 

Then what is the use of Marker interface in Java?
Normally interface used to tell compiler about the behavior of the class. Used to tag the implementation of class based on their purpose and behavior. Just used to "mark" the java class which support a certain capability.

Alternate for Marker or Tag interfaces?
Java 1.5 came up with Annotations as an alternate solution for Marker interfaces. Advantage of using annotations are just it makes loose coupling instead of implementing marker interfaces. 
By using Annotations we can easily specify special behavior to the class but it can't act as the super type of the class what we can achieve by Marker interface. 

Is there any Marker interfaces provided by Java?
Below are the list of marker interfaces provided by Java

  • Cloneable
  • Serializable
  • EventListener
  • RandomAccess
  • SingleThreadModel
  • Remote

Advantage of using Marker interface?
Apart from using Java built-in Marker interfaces, we can also create our own Marker interfaces for our application specific needs like classify code, logically to divide the code which does its own process at run-time. For example when we go for API or framework development Marker interface plays the important role like we have in Spring, Struts etc.,

Lets see simple example of using Marker interface in Java


public interface MyMarker {
 // Marker interface without any methods or variables 
}



public class MyMarkerTest implements MyMarker {
 
 public static void main(String[] args) {
  
  MyMarkerTest obj = new MyMarkerTest();
  
  if (obj instanceof MyMarker) {
   System.out.println("obj is an instance of MyMarker");
  } else {
   System.out.println("obj is NOT an instance of MyMarker");
  }
 }
}


OUTPUT:


obj is an instance of MyMarker