what is a marker interface in java
A marker interface in Java is an interface with no methods or fields; it acts as a tag to inform the compiler that the classes implementing it should be treated differently. Marker interfaces are also known as tag interfaces. They simply mark or tag a class to indicate that it possesses a certain property or behavior.
One common use case for marker interfaces is in frameworks or APIs where the presence of a marker interface implies some sort of contract or special handling.
Here’s an example of a marker interface in Java:
/*
* Author: Zameer Ali
* */
// Marker Interface
public interface Printable {
// Marker interfaces have no methods or fields
}
// Classes implementing the marker interface
class Document implements Printable {
// Class implementation
}
class Image {
// Class implementation
}
// Utility class that processes printable objects
class PrintProcessor {
public static void print(Object obj) {
if (obj instanceof Printable) {
System.out.println("Printing...");
// Logic to print the object
} else {
System.out.println("Cannot print this object.");
}
}
}
public class MarkerInterfaceExample {
public static void main(String[] args) {
Document document = new Document();
Image image = new Image();
// Using the PrintProcessor to print objects
PrintProcessor.print(document); // Output: Printing...
PrintProcessor.print(image); // Output: Cannot print this object.
}
}
In this example, Printable
is a marker interface with no methods. The Document
class implements the Printable
interface, indicating that it can be printed. The Image
class does not implement the Printable
interface.
The PrintProcessor
class has a print
method that takes an Object
as a parameter. It checks if the object is an instance of the Printable
interface. If it is, the object is considered printable, and the logic to print the object can be executed. Otherwise, a message indicating that the object cannot be printed is displayed.
Marker interfaces are used sparingly in modern Java development, as annotations and other techniques have largely replaced them. However, they provide a clear and simple way to convey metadata about classes.