Tag or marker interfaces

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:

The advantages of doing so are:

See Also :
Immutable objects
Would you use this technique?
Yes   No   Undecided   
© 2017 Hirondelle Systems | Source Code | Contact | License | RSS
Individual code snippets can be used under this BSD license - Last updated on September 21, 2013.
Over 2,000,000 unique IPs last year - Built with WEB4J.
- In Memoriam : Bill Dirani -