What is Marker Interface in Java: Definition and Examples
marker interface in Java is an interface with no methods or fields that signals to the compiler or JVM that a class has a special property. It acts like a tag to provide metadata about the class without adding behavior.How It Works
A marker interface works like a simple label or tag you put on a class to tell the Java system something special about it. Imagine putting a sticker on a box to show it contains fragile items. The sticker itself doesn't do anything, but it tells the handler to be careful.
In Java, when a class implements a marker interface, the compiler or runtime can check for that interface and change how it treats the class. For example, the Serializable marker interface tells Java that objects of the class can be saved to a file or sent over a network.
Because marker interfaces have no methods, they don't force the class to add any code. They just provide information that other parts of the program or Java itself can use.
Example
This example shows a simple marker interface called MyMarker and a class that implements it. The program checks if the object has the marker and prints a message.
interface MyMarker { // No methods or fields } class MyClass implements MyMarker { // Normal class code } public class Main { public static void main(String[] args) { MyClass obj = new MyClass(); if (obj instanceof MyMarker) { System.out.println("Object is marked with MyMarker interface."); } else { System.out.println("Object is NOT marked."); } } }
When to Use
Use marker interfaces when you want to give a class a special property without adding methods. They are useful for signaling to Java or your own code that the class should be treated differently.
Common real-world uses include:
- Serialization: The
Serializableinterface marks classes whose objects can be saved or sent. - Cloning: The
Cloneableinterface marks classes that allow object copying. - Custom tagging: You can create your own marker interfaces to mark classes for special processing in your application.
Marker interfaces help keep your code clean by separating the "tag" from actual behavior.
Key Points
- A marker interface has no methods or fields.
- It acts as a tag to provide metadata about a class.
- Java uses marker interfaces like
SerializableandCloneable. - It helps the compiler or runtime treat classes differently.
- You can create your own marker interfaces for custom tagging.