A Marker interface is an interface with no variables and methods, in simple words, we can say that an empty interface in java is called a marker interface.
Serializable, Cloneable, Remote Interface are some of the examples of Marker Interface. In this article, we will discuss the uses of Marker interface in Java.
What is the use of Marker Interface?
When we look closely the marker interface doesn’t have any methods in it, so then comes the question what is the use of it then?
If you look closely Serializable, Cloneable, Remote Interface it looks like they will indicate something to compiler or JVM. So if the JVM sees Clonnable it performs some operation to support cloning. Same applies to the Serializable and other marker interfaces as well.
Why can this indication not be done using a flag variable?
So now we know the what is the use of a marker interface, now again comes a question that why it cannot be done using a flag variable. Yes, you can do it using a flag variable but by using a Marker Interface you can have a more readable code.
Later from Java 1.5, the need for the marker interface is eliminated by the introduction of Java Annotation feature. It will be a good option to use the annotation rather than marker interface as annotations will have more advantages than a marker interface.
Custom Marker Interface in Java
In the above code, we have created a Marker Interface (MyMarker). In the implementation class, we have created the special method checkMarker(), which verifies that the passing object is an instance of marker interface, if yes then JVM will perform the special operation mentioned inside.
package com.javainterviewpoint; public class MyMarkerImpl implements MyMarker { public static void main(String[] args) { MyMarkerImpl myMarkerImplObj = new MyMarkerImpl(); checkMarker(myMarkerImplObj); } public static void checkMarker(Object obj) { if(obj instanceof MyMarker) { System.out.println("Our Custom Marker"); } } }
List of Marker Interfaces in Java
- java.lang.Cloneable
- java.util.EventListener
- java.io.Serializable
- java.rmi.Remote
- javax.servlet.SingleThreadModel
- javax.ejb.EnterpriseBean
- java.util.RandomAccess
Leave a Reply