A tag interface (also called a marker interface) is simply an interface with no methods. Some examples of tag interfaces from the JDK:
Why define an interface with no methods? Since there are no methods, a tag interface can never define behavior, at least not in the typical sense. However, even though it has no methods, a tag interface always carries type information. In some cases, type information itself can be used to solve a problem.
For example, Java's serialization mechanism requires an object to implement Serializable before it will serialize it. As stated in its javadoc:
The serialization interface has no methods or fields and serves only to identify the semantics of being serializable.
Tools will often use instanceof or reflection to inspect objects, to see if they implement a given tag interface. But this isn't the only way a tag interface can be useful. There are some common cases for which you might consider defining your own tag interface, even without any corresponding use of instanceof or reflection:
- immutable objects (or immutable classes, if you prefer)
- singleton classes
- it emphasizes important, high-level aspects of a class, not otherwise expressed in code.
- for both human readers and tools, it allows quick identification of classes having specific properties.
- the javadoc of the tag interface is a natural home for documenting all the characteristics of items that implement the given interface.