Marker interface in Java is an interface with no fields and methods. It is empty interface in java that is called marker interface. It provides run-time type information about objects so that compiler and JVM have additional information about the object.
Examples of marker interface are Serializable
, Clonnable
, ThreadSafe
and Remote
interface. All these interfaces are empty interfaces.
Use of marker interface in Java is to indicate something to compiler or JVM that the class implementing any of these would have some special behavior.
Hence, if the JVM sees a class is implementing the Serializable
interface it does some special operation on it and writes the state of the object into object stream. This object stream is then available to be read by another JVM.
Similarly if JVM finds that a class is implementing Clonnable
interface, it performs some special operation in order to support cloning. The same theory goes for RMI and Remote
interface. This indication (to the JVM) can also be done using a boolean
flag or a String
variable inside the class. The ThreadSafe
interface is a marker interface which can be used to communicate to other developers that classes implementing this marker interface give thread-safe guarantee and any modification should not violate that.
But then another question arises, why this indication cannot be done using a flag inside a class? Answer is YES, this can be done by using a boolean
flag or a String
but marking a class like Serializable
or Clonnable
makes it more readable and it also allows to take advantage of polymorphism in Java.
Hope you have enjoyed reading What is marker interface in Java?. Please do write us if you have any suggestion/comment or come across any error on this page. Thank you for reading!
Share this page on WhatsApp