Skip to main content

Marker Interface in Java: what, why, uses, etc.

What are Marker Interfaces in Java?

An empty interface having no methods or fields/constants is called a marker interface or a tag interface. This of course means if the interface is extending other interfaces (directly or indirectly) then the super interfaces must not have any inheritable member (method or field/constant) as otherwise the definition of the marker interface (an entirely empty interface) would not be met. Since members of any interface are by default '
public' so all members will be inheritable and hence we can say for an interface to be a marker interface, all of its direct or indirect super interfaces should also be marker. (Thanks marco for raising the point. I thought it was obvious, but mentioning all this explicitly would probably help our readers.)

There are few Java supplied marker interfaces like
Cloneable, Serializable, etc. One can create their own marker interfaces the same way as they create any other interface in Java.

Purpose of having marker interfaces in Java i.e., why to have marker interfaces?

The main purpose to have marker interfaces is to create special types in those cases where the types themselves have no behavior particular to them. If there is no behavior then why to have an interface? Because the implementor of the class might only need to flag that it belongs to that particular type and everything else is handled/done by some other unit - either internal to Java (as in the case of Java supplied standard marker interfaces) or an app specific external unit.

Let's understand this by two examples - one in which we will discuss the purpose of a standard Java interface (
Cloneable) and then another user-created marker interface.

What purpose does the Cloneable interface serve?

When JVM sees a
clone() method being invoked on an object, it first verifies if the underlying class has implemented the 'Cloneable' interface or not. If not, then it throws the exception CloneNotSupportedException. Assuming the underlying class has implemented the 'Cloneable' interface, JVM does some internal work (maybe by calling some method) to facilitate the cloning operation. Cloneable is a marker interface and having no behavior declared in it for the implementing class to define because the behavior is to be supported by JVM and not the implementing classes (maybe because it's too tricky, generic, or low-level at the implementing class level). So, effectively marker interfaces kind of send out a signal to the corresponding external/internal entity (JVM in case of Cloneable) for them to arrange for the necessary functionality.

How does JVM support the 'cloning' functionality - probably by using a native method call as cloning mechanism involves some low-level tasks which are probably not possible with using a direct Java method. So, a possible 'Object.clone' implementation would be something like this:-


public Object clone() throws CloneNotSupportedException {

 if (this implements Cloneable)

     return nativeCloneImpl();

 else

     throw new CloneNotSupportedException();

}


Anyone wondered as to why and when do we get '
CloneNotSupportedException' exception at compile-time itself? Well... that's no trick. If you see the signature of the 'Object.clone()' method carefully, you will see a throws clause associated with it. I'm sure how can you get rid of it: (i) by wrapping the clone-invocation code within appropriate try-catch (ii) throwing the CloneNotSupportedException from the calling method.

What purpose does a user-defined marker interface serve? It can well serve the same purpose as by any standard marker interface, but in that case the container (the module controlling the execution of the app) has to take the onus of making sure that whenever a class implements that interface it does the required work to support the underlying behavior - the way JVM does for
Cloneable or any other standard marker interface for that matter.

Defining an user-defined marker interface in Java

Let's define a user-defined marker interface. Let's say there is an app suporting a medical store inventory and suppose you need a reporting showing the sale, revenue, profit, etc. of three types of medicines - allopathic, homeopathic, and ayurvedic separately. Now all you need is to define three marker interfaces and make your products (medicines) implement the corresponding ones.


public interface Allopathic{}
public interface Homeopathic{}
public interface Ayurvedic{}


In your reporting modules, you can probably get the segregation using something similar to below:-


for (Medicine medicine : allMedicines) {
if (medicine instanceof Allopathic) {
//... update stats accordingly
}
else if (medicine instanceof Homeopathic) {
//... update stats accordingly
}
else if (medicine instanceof Ayurvedic) {
//... update stats accordingly
}
else {
//... handle stats for general items
}
}


As you can see the medicines themselves don't need to implement any specific behavior based on whether they are allopathic, homeopathic, or ayurvedic. All they need is to have a way of reflecting which category they belong to, which will in turn help the reporting modules to prepare the stats accordingly.

Now this can be done by having a flag as well... yeah, sure it can be. But, don't you think tagging a class makes it more readable than having a flag indicating the same. You kind of make it an implementation-independent stuff for the consumers of your classes. If your class implements an interface, it becomes part of the class signature of the published API. Otherwise, you would probably handle the situation by having a public final field having the flag set up at the time of instantiation - final because you would not like others to change it. I guess going the marker interface way would probably make more sense in many such situations.

Another advantage of going via marker interface way is that at any point of time you can easily cast the objects of the implementing classes. Again it's not that if you go via public final approach, you can't do that. You can very well do, but casting might look a cleaner approach in many situations.

The bottom-line is there will hardly be any enforced need for a designer/developer to go via that way as there can be possible alternatives, but marker interfaces can surely be a preferred choice for some in some cases.

 

Comments

Popular posts from this blog

Advantages & Disadvantages of Synchronous / Asynchronous Communications?

  Asynchronous Communication Advantages: Requests need not be targeted to specific server. Service need not be available when request is made. No blocking, so resources could be freed.  Could use connectionless protocol Disadvantages: Response times are unpredictable. Error handling usually more complex.  Usually requires connection-oriented protocol.  Harder to design apps Synchronous Communication Advantages: Easy to program Outcome is known immediately  Error recovery easier (usually)  Better real-time response (usually) Disadvantages: Service must be up and ready. Requestor blocks, held resources are “tied up”.  Usually requires connection-oriented protocol

WebSphere MQ Interview Questions

What is MQ and what does it do? Ans. MQ stands for MESSAGE QUEUEING. WebSphere MQ allows application programs to use message queuing to participate in message-driven processing. Application programs can communicate across different platforms by using the appropriate message queuing software products. What is Message driven process? Ans . When messages arrive on a queue, they can automatically start an application using triggering. If necessary, the applications can be stopped when the message (or messages) have been processed. What are advantages of the MQ? Ans. 1. Integration. 2. Asynchrony 3. Assured Delivery 4. Scalability. How does it support the Integration? Ans. Because the MQ is independent of the Operating System you use i.e. it may be Windows, Solaris,AIX.It is independent of the protocol (i.e. TCP/IP, LU6.2, SNA, NetBIOS, UDP).It is not required that both the sender and receiver should be running on the same platform What is Asynchrony? Ans. With messag

XML Binding with JAXB 2.0 - Tutorial

Java Architecture for XML Binding (JAXB) is an API/framework that binds XML schema to Java representations. Java objects may then subsequently be used to marshal or unmarshal XML documents. Marshalling an XML document means creating an XML document from Java objects. Unmarshalling means creating creating a Java representation of an XML document (or, in effect, the reverse of marshaling). You retrieve the element and attribute values of the XML document from the Java representation. The JAXB 2.0 specification is implemented in JWSDP 2.0. JAXB 2.0 has some new features, which facilitate the marshalling and unmarshalling of an XML document. JAXB 2.0 also allows you to map a Java object to an XML document or an XML Schema. Some of the new features in JAXB 2.0 include: Smaller runtime libraries are required for JAXB 2.0, which require lesser runtime memory. Significantly, fewer Java classes are generated from a schema, compared to JAXB 1.0. For each top-level complexType, 2.0 generates a v