What is the use of marker interfaces in Java?
It indicates that the class (and consequently all the fields which aren't transient) are candidates for serialisation. And if you're building a framework reliant on serialisation, you can of course write a method thus:
public void registerObject(Serializable obj);
to limit the classes you're prepared to accept.
Because a serialized object needs to retain compatibility across systems, serialisation is an explicit design decision and hence requires the use of the marker interface, to identify such candidates.
There's also a security aspect. You don't want to make everything serialisable - otherwise you can accidentally expose (say) passwords or other sensitive data via serialisation.
Joshua Bloch: Effective Java 2nd Edition, p 179
Item 37: Use marker interfaces to define types
... You may hear it said that marker annotations (Item 35) make marker interfaces obsolete. This assertion is incorrect. Marker interfaces have two advantages over marker annotations. First and foremost, marker interfaces define a type that is implemented by instances of the marked class; marker annotations do not. The existence of this type allows you to catch errors at compile time that you couldn’t catch until runtime if you used a marker annotation....
Personally I think I'll bow to Joshua's superior knowledge on this subject.
Such marker interfaces are useful in the case other code takes decisions depending on whether an object implements some marker interface.
In the case of Serializable
, reflection will be used to serialize the fields of the objects.
Now annotations are preferred as they don't propagate to sub-classes.
See Marker interface pattern.
In earlier versions of Java, Marker Interfaces were the only way to declare metadata about a class. For example, the Serializable Marker Interface lets the author of a class say that their class will behave correctly when serialized and deserialized.
In modern Java, marker interfaces have no place. They can be completely replaced by Annotations, which allow for a very flexible metadata capability. If you have information about a class, and that information never changes, then annotations are a very useful way to represent it.