Member-only story
Effective Java! Use Marker Interfaces to Define Types
In this chapter marker interfaces and marker annotations are discussed. A marker interface is an interface that has no method declarations but simply is used to mark an implementing class as having a certain attribute. An example of a marker interface is the Serializable
interface built into the core of Java. Another similar thing you may hear about is of marker annotations. These serve a similar purpose of marking a specific item as having an attribute but, as the name suggests, uses an annotation instead of an interface to accomplish its task. So should we use one versus the other?
Marker interfaces, as all interfaces do, define a type. This is really where the core of when they should be used comes from. In defining a type we allow ourselves to use that power to help us at compile time. Let’s consider the above example of Serializable
. The main consumer of this interface, ObjectOutputStream.write
, could use this ability of knowing it requires an object of the Serializable
type to define it's write
method as taking a Serializable
object. If this was done we would know at compile time (or more likely coding time because of our IDE's help) when we were trying to pass an object that isn't going to work to this method. Unfortunately the designer of this class didn't take the opportunity to make the interface this way and it instead takes an Object
but it still is instructive of a good potential use for a marker interface. Other times when we should use a marker interface is when we see that marker interface as only…