what is Marker interface in java with example

          One of the useful technique in java is marker interface. What is Marker interface? Why and when it is required?. Can you create your  custom (own)  marker interface?  These are  some of the questions about marker interface  asked in core java interviews.  Before start with  marker interface , let us brief about interface.  As we know, an interface is a named set of  method definitions  (and/or constant data elements) for which an implementer must provide code.  Methods defined in an inlterface have no method body. The  implementer of the interface is responsible for providing the method body.

                   Marker interface is  an interface that does not contain any method declarations and constants at all (i.e. interface with no members) but  to mark a class that implements the interface as legal to do special operation on that object OR to indicate a class  as having certain desirable properties.  As marker interface has no method declarations  , no need to write any extra methods in a class that implements the  empty interface.
marker  interface is defined as given below

public interface  interfaceName {
}
You can understand very well by going through some of the below examples of the application of marker interfaces from the Java programming language.
1. Serializable
2. java.util.RandomAccess
3. Cloneable
4. EventListner
5. SingleThreadModel
6. Remote

Before going to the examples  , let us answer the following questions?
1. Can you  serialize the state of an object  for its particular class which is not Serializable using writeObject() method  of  ObjectOutputStream class ?
2. Can you clone (shallow copy)  a  object which is not marked as Cloneable  using the clone() method of object?

The answer is no. The concerned classes are need to be marked or indicated  as legal for those methods to do the specified operation.  How to mark those objects as legal?. The best way is to  implement the class  with the special interface called marker  interface . The methods (for e.g. clone() and writeObject() )  that do the special operations (cloning , serialization)  will do  the check whether the object of the class is marked as legal (i.e. whether the object is  instance of marker Interface type or  instance of the class that implements the marker interface) .  If it is not marked as legal , then the method throws errors.   for eg.   NotSerializableException is thrown by writeObject()  method,  CloneNotSupportedException is thrown by the clone() method.

1. Let us take the Serializable interface  

public interface Serializable {}
One of the example of the application of marker interfaces from the Java programming language  is  Serializable interface.  By implementing this interface, a class indicates that its non-transient data members can be written to an ObjectOutputStream .    The  method writeObject() of ObjectOutputStream class will do  many instanceof  checks  as given below  to determine writabilty, one of which checks  for the Serializable interface. If any of  these tests fails, the method throws a NotSerializableException. That means an attempt to call ObjectOutputStream.writeObject()  on an object that doesn’t implement Serializable will fail  at run time,

 

2.    Cloneable – a Marker interface
public interface Cloneable {}

                    A class implements the Cloneable interface to indicate to the Object.clone() method that it is legal for shallow copy  ( to make a field-for-field copy of instances of that class) and  CloneNotSupportedException  is thrown to indicate that the clone() method has been called to clone an object, but that the object’s class does not implement the Cloneable interface
Many classes in  Java (such as  Date and Calendar)   implement Cloneable as given below
                          public abstract class Calendar extends Object implements Serializable, Cloneable
               Thus, the instances of these classes can be cloned. For example, the following code clones a calender object.
          Calendar rightNow = Calendar.getInstance();  //    getInstance method returns a Calendar object whose time fields have been initialized with the current date and time:
         Calendar calender_Clone1 = (Calendar)rightNow.clone();
3.  java.util.RandomAccess is also a Marker interface
public interface RandomAccess { }
           RandomAccess Marker interface is implemented by  Lists (For e.g. ArrayList) to indicate that they support  random access. Java provides many Lists that  may be either random  or sequential access lists.  Both requires different algorithms  to provide good performance for manipulating  the lists.  The best algorithms for manipulating random access lists (such as ArrayList) may give poor performance when applied to sequential access lists (such as LinkedList).
                 So to write generic algorithms , it is required to check whether the given list supports  fast random access  or sequential access .  For this purpose, RandomAccess marker interface is created and  it is assumed that a List that implements this interface supports  random access.  Now the generic algorithms can be written  by checking the given list is an instanceof RandomAccess interface before  applying an algorithm.
4.  EventListner :
                        All event listener types are interfaces that extend the java.util.EventListener interface. This tagging / marker  interface  does not declare any methods but you can use the instanceof operator to distinguish event listeners from other object types.
5.  SingleThreadModel :
                     The marker interface, meaning  does not declare any methods but  it  indicates to the servlet container that the servlet is not thread-safe, and to  handle only one request at a time in its service( ) method.

Create  marker interface for your application :
You can create your own marker interface which is suitable for your application.  Let us create our own very simple marker interface as given below

In the above example code ,  allow method of CheckAndAllow class accepts only  the object of the class that implements the Allowable interface. If you send the object’s class does not implement the Allowable interface, NotAllowableException  exception is thrown.

Is Marker interface  obsolete? 

     You may heard that marker annotation is the replacement for marker interface. There is no reason  to say that marker interface is obsolete. Both have merits and demerits. Although java annotation is a useful and powerful feature introduced in java 5.0 , marker interfaces are still used by still frameworks such as Spring , Struts.  For eg. Spring framework provides many marker interfaces  to change the behavior of your bean in the BeanFactory.  Some of the below good reasons make marker interface still alive.
1. Marker interface  makes the code more readablilty and understandability where as so many annotations may lead to poor code readability and understandability.
2. If you define a reference variable whose type is an interface / marker interface , any object you assign to it must be an instance of a class / marked class that implements the interface. Assigning other objects of class that does not implement the interface , throws compile time errors.
3. With marker interface , a simple  “instanceof”  check is required to check the class is marked by  interface as we seen in the code of own marker interface.   But with annotation , you need  to use reflection or  similar  mechanism to check the class has the desired @annotation.

 

You may also like

Leave a Reply