A Marker Interface in Java is an empty interface (without methods) used to “mark” a class. This marker provides special behavior to the JVM or a framework.
The presence of the marker interface signals that the class should be treated differently.
Definition
A marker interface is simply an interface with no methods.
interface MarkerInterface {
}
The interface does not define methods but acts as a marker for special behavior.
Example: Serializable Interface
One of the most common marker interfaces in Java is Serializable.
import java.io.Serializable;
class Person implements Serializable {
String name;
int age;
}
If a class implements Serializable, the JVM allows the object to be converted into a byte stream for storage or transmission.
Example of Custom Marker Interface
interface Marker {}
class Test implements Marker {
}
public class Demo {
public static void main(String[] args){
Test t = new Test();
if(t instanceof Marker){
System.out.println("Marker interface detected");
}
}
}
The program checks whether the object implements the marker interface and applies special behavior.
Common Marker Interfaces in Java
- Serializable
- Cloneable
- RandomAccess
- SingleThreadModel (deprecated)
Marker Interface vs Annotation
Modern Java often uses annotations instead of marker interfaces.
- Marker Interface → checked using instanceof
- Annotation → checked using reflection
Example annotation:
@interface MarkerAnnotation {
}
Real World Example
Consider a framework that processes objects differently depending on whether they implement a marker interface.
Example use cases:
- Serialization frameworks
- Security checks
- Special processing rules
- Framework configuration
Quick Summary
- A marker interface is an empty interface
- It signals special behavior to the JVM or frameworks
- Examples include Serializable and Cloneable
- Modern Java often prefers annotations instead
0 comments