What are marker interfaces in Java?
A marker interface is an interface that declares no methods or fields. Its sole purpose is to tag a class as possessing some property, which the JVM, runtime, or framework can then detect via `instanceof` checks. The interface conveys metadata rather than defining a behavioral contract.
The canonical examples in the Java standard library are: - `java.io.Serializable` — signals that a class's instances can be serialized to a byte stream. The `ObjectOutputStream` checks `instanceof Serializable` before attempting serialization and throws `NotSerializableException` if the check fails. - `java.lang.Cloneable` — signals that `Object.clone()` may be called on instances. Without implementing `Cloneable`, `clone()` throws `CloneNotSupportedException`. - `java.util.RandomAccess` — signals that a `List` implementation supports O(1) indexed access, allowing algorithms like `Collections.binarySearch()` to use a faster iteration strategy.
The mechanism works through runtime type checking: `if (obj instanceof Serializable)`. The interface itself provides no methods — the behavior is implemented elsewhere (in `ObjectOutputStream`, in `Object.clone()`, etc.).
Modern Java offers annotations as an alternative that is generally considered more expressive. Instead of `implements Serializable`, you could annotate a class with something like `@Serializable`. Annotations can carry parameters, are accessible through the reflection API (`getAnnotation()`), and can target specific elements (fields, methods, parameters). Marker interfaces, by contrast, apply only to classes and interfaces and cannot carry data.
However, marker interfaces have one advantage: they participate in the type system. You can write a method signature `void serialize(Serializable obj)` and get compile-time enforcement. An annotation-based equivalent requires runtime reflection checking.
For new code, prefer annotations unless compile-time type checking is specifically needed.
Defines a marker interface as method-less, names at least two standard examples, and explains the instanceof-based detection mechanism.
Also compares marker interfaces to annotations as an alternative, explains the type-system advantage of interfaces, and identifies when each approach is preferable.
Reading the answer is step one. Explaining it unprompted — under interview pressure — is what actually matters. Get AI-graded feedback on your answer with follow-up probes on your weak points.
Get Graded — Free Assessment