What is a Marker Interface?
Marker Interface
A Marker Interface is an interface in Java that contains no methods or fields. It acts as a “tag” or “marker” to convey metadata to the JVM or compiler, enabling certain functionalities or behaviors in classes that implement these interfaces. An Interface that does not have any declaration inside but still enforces a mechanism is called a Marker Interface.
The purpose of a marker interface is to indicate that a class possesses a specific property or capability without enforcing any method implementation.
Characteristics of Marker Interfaces
The key characteristics of marker interfaces are as follows:
- No Methods or Fields: Marker interfaces are empty.
- Behavioral Tags: Used to “mark” classes for special behavior.
- Compiler/Runtime Role: Functionality depends on how JVM, libraries, or frameworks interpret the marker.
Examples
Some examples of Marker Interface are as follows:
Serializable
This interface is used to indicate that a class’s objects can be serialized (converted into a byte stream).
import java.io.Serializable;
public class Employee implements Serializable {
private int id;
private String name;
public Employee(int id, String name) {
this.id = id;
this.name = name;
}
}
Cloneable
This interface indicates that a class’s objects can be cloned using the clone() method from the Object class.
Alternatives to Marker Interfaces
Since Java 5, annotations have largely replaced marker interfaces for similar purposes as they offer more flexibility and metadata.
In earlier versions of Java, Marker Interfaces were the only way to declare metadata about a Java class. In later versions of Java, Marker interfaces can be replaced by Annotations. Annotations allow flexible metadata capability.
Java Tutorials
Java Tutorial on this website: