What is a marker interface?

A marker interface is an interface that does not contain any methods or constants. Its purpose is to provide metadata about a class to the JVM or application framework. By implementing a marker interface, a class indicates that it supports a specific capability or should receive special treatment during runtime processing.

Key Points:

• Marker interfaces do not declare any methods. • They are used to identify classes with specific characteristics or behaviors. • The JVM and frameworks can check for marker interfaces using instanceof or reflection. • Common examples include Serializable and Cloneable. • Marker interfaces help enforce type safety compared to using annotations in some scenarios.

Example:

The Serializable interface is a classic marker interface. When a class implements Serializable, it tells the JVM that objects of that class can be converted into a byte stream for storage or network transmission.

Code Example:

import java.io.Serializable;

class Employee implements Serializable {
    private int id;
    private String name;
}

public class Main {
    public static void main(String[] args) {
        Employee emp = new Employee();

        if (emp instanceof Serializable) {
            System.out.println("Employee object can be serialized.");
        }
    }
}

Interview Tip:

A concise interview answer is: "A marker interface is an empty interface used to provide metadata about a class. It does not define any methods but signals the JVM or frameworks that the implementing class supports a specific capability, such as serialization through the Serializable interface."