What are tagging interfaces and what are they used for?
Because sometimes, it really makes sense if some property of a type can be used as a type itself - Serializable
comes to mind. If I make a method like this:
public void save(Object data){ ... }
... you don't really know how that data
will be saved. VM serialization? Bean property serialization? Some homebrewed scheme? Whereas if you write it like this:
public void save(Serializable data){ ... }
... it is quite clear (if only the designer of ObjectOutputStream
had used this possibility!). Sometimes it makes sense to use annotations when you want to add meta-data to types, but in this case, I'd argue for a tagging interface.
It was used to mentioned some property of a class (like Serializable shows, that the class is allowed to serialize). Now annotations could do this job.
tagging interfaces are interfaces with no abstract methods inside , they are used to add a data type for the class which implements them and to be a parent interface for other interfaces ( especially with multiple inheritance in interfaces )
public interface name {}
public interface john1 {}
public interface john2 {}
public interface Demo extends john1 , john2 , name {}
** when JVM sees the name interface , it will find out that the Demo will exert a specific cenario .
A tagging interface typically has some magic associated with it: either directly built into the VM, or using reflection. Because the magic could technically apply to any class, you use the tagging to indicate that you thought well about the magic and whether it applies to your class.
In addition to the other answers marker interfaces can also be used to specify additional properties of a class that is not inherited by some other already-implemented interface. One example of this would be the interface RandomAccess. It denotes a collection that can be accessed randomly without loss of performance and does not have to be accessed via an iterator to achieve that performance.
You can tag your class with a tagging interface to say to your fellow developer and consumer of your class that you explicitely support that functionality. Think of Serializable; someone who needs to persist a Session and uses serialization to do that can safely use an object of your class.
It can be further used in reflection; nowadays it is common to use annotations to do this but in the olden days you can inspect a class, check whether it implements a certain interface (like DAO) and if so, process the object further (I'm thinking about the Entity annotation here).