library
intermediateMarker Interfaces
Understand Serializable, Cloneable, and the marker interface pattern — and when annotations replaced it.
A marker interface is an interface with no methods. It 'marks' a class as having a certain property. The JVM or frameworks check for the marker using instanceof.
A marker interface = a wristband at a concert. It doesn't change what you can do, but security checks for it before letting you into the VIP area.
Key Concepts
1
Classic marker interfaces:
- Serializable: marks a class as safe for serialization. ObjectOutputStream checks instanceof Serializable before writing.
- Cloneable: marks that Object.clone() should work. Without it, clone() throws CloneNotSupportedException.
- RandomAccess: marks List implementations with O(1) indexed access (ArrayList). Algorithms use this to choose between indexed loops and iterators.
2
Marker interface vs annotation:
- Marker interfaces define a type — you can use them as parameter types (void process(Serializable obj)).
- Annotations don't define a type — they're metadata only.
- Marker interfaces are checked at compile time via the type system. Annotations are checked at runtime via reflection.
- When you need to restrict a method parameter to 'marked' classes, use a marker interface. When you just need metadata, use an annotation.
3
Effective Java recommends: if the marker is used as a type (method parameters, return types), use a marker interface. If it's just metadata for processing, use an annotation.