Latest Entries »

Monday, November 2, 2009

Marker Interface in Java

Marker Interface most of the people know the definition, but many of them are not aware of the purpose of the Marker Interface and how it works. Very often I heard the question from my friends that the Marker Interface doesn't have methods then what is the use of Marker Interface.

One of the basic feature of Java Programing Language is that it mandates a separation between Interfaces and Classes. Interfaces are used in Java to specify the behavior of the derived class.

While working on the Java Programing Language many of the programmers might have observed the Interfaces which doesn't have no behavior. In other words they are just empty Interface definitions. These Interfaces are knows as Marker Interfaces.

Basic Definition: Interfaces with empty body.
Example: Serializable, Cloneable, Remote, EventListener


Marker Interfaces are also called as Tag Interfaces because they tag all the derived classes into a category based on their purpose. If we consider a real time example for this scenario, lets pick Cloneable from the abouve examples given. All classes that implement Cloneable Interface can be cloned by calling clone(); method. Now the Java Compiler checks to make sure that if the clone(); method is called on a class and the class implements the Cloneable Interface. If we have the Object obj and call clone(); method on this as

MyObject obj = new MyObject();
MyObject ref = (MyObject)(obj.clone());

Here if the MyObject doesn't implement the Cloneable Interface and Cloneable is not implemented any of the super class that MyObject inherits from, the compiler will mark this line as error. This is because the clone() method may only be called by objects of the type Cloneable.

Here our Cloneable Interface is an Interface with empty body, but still it serving a major role.

To create a copy of any Object, in our case we have MyObject to create a clone for this Object we need to have a clone(); method which should implement Cloneable Interface.

The above scenario clearly states that we are marking the class Cloneable so that the Object can be Cloneable. For this purpose we have Marker Interfaces in Java.

When ever we implement Serializable, Cloneable JVM understands that this thing is to be serialized or cloned and no methods involved in this process.

Hope this article will clear your ambiguities about Marker Interfaces.

0 comments: