What is a marker interface, and can you give examples?
Quick Answer
A marker interface has no methods or fields — it exists purely to tag a class with metadata that other code checks via instanceof or reflection. Classic examples include Serializable, Cloneable, and RandomAccess. Annotations (like @Deprecated or custom ones) have largely replaced marker interfaces for new APIs, since they carry richer metadata.
Detailed Answer
A marker interface declares no methods at all — implementing it adds no new behavior directly, but signals to the JVM or a library that instances of the class should be treated specially.
Classic JDK examples:
Serializable: marks a class as eligible for Java serialization;ObjectOutputStreamchecksinstanceof Serializablebefore writing an object, throwingNotSerializableExceptionotherwise.Cloneable: marks a class as allowingObject.clone()to succeed; without it, callingclone()throwsCloneNotSupportedException.RandomAccess: marks aListimplementation (likeArrayList) as supporting fast, O(1) indexed access, letting algorithms (e.g.,Collections.binarySearch) choose an index-based loop instead of an iterator-based one for better performance.
class Point implements Serializable {
int x, y; // now writable via ObjectOutputStream
}
Why they exist: before annotations (Java 5), tagging a class for special treatment required some type-level mechanism checkable via instanceof — an interface with no members was the idiom.
Modern alternative: annotations (@Deprecated, @FunctionalInterface, or custom ones processed via reflection) are now generally preferred for new APIs, since they can carry additional metadata (values, targets, retention) that a bare marker interface can't. Marker interfaces persist mainly for backward compatibility and cases (like Serializable) baked deeply into the platform.