Monday, January 2, 2012

What is Marker interfaces in Java and why required

Marker interface in Java is interfaces with no field or methods or in simple word empty interface in java is called marker interface. Example of market interface is Serializable, Clonnable and Remote interface. Now if marker interface doesn't have any field or method or behavior they why would Java needs it? This was asked to my friend in one of his core java interview and then I thought to touch based on it. In this article we will see couple of reason on what marker interface do in Java and what is use of marker interface in Java. Marker interface are also called tag interface in Java.

What is Marker interfaces in Java and why required

Why Marker or Tag interface do in Java

1) Looking carefully on marker interface in Java e.g. Serializable, Clonnable and Remote it looks they are used to indicate something to compiler or JVM. So if JVM sees a Class is Serializable it done some special operation on it, similar way if JVM sees one Class is implement Clonnable it performs some operation to support cloning. Same is true for RMI and Remote interface. So in short Marker interface indicate, signal or a command to Compiler or JVM.

marker interfaces java example tutorialThis is pretty standard answer of question about marker interface and once you give this answer most of the time interviewee definitely asked "Why this indication can not be done using a flag inside a class?” this make sense right? Yes this can be done by using a boolean flag or a String but doesn't marking a class like Serializable or Clonnable makes it more readable and it also allows to take advantage of Polymorphism in Java.

Where Should I use Marker interface in Java

Apart from using built in marker interface for making a class Serializable or Clonnable. One can also develop his own marker interface. Marker interface is a good way to classify code. You can create marker interface to logically divide your code and if you have your own tool than you can perform some pre-processing operation on those classes. Particularly useful for developing API and framework like Spring or Struts.
After introduction of Annotation on Java5, Annotation is better choice than marker interface and JUnit is a perfect example of using Annotation e.g. @Test for specifying a Test Class. Same can also be achieved by using Test marker interface.


Another use of marker interface in Java

One more use of marker interface in Java can be commenting. a marker interface called Thread Safe can be used to communicate other developers that classes implementing this marker interface gives thread-safe guarantee and any modification should not violate that. Marker interface can also help code coverage or code review tool to find bugs based on specified behavior of marker interfaces.
Again Annotations are better choice @ThreadSafe looks lot better than implementing ThraedSafe marker interface.

In summary marker interface in Java is used to indicate something to compiler, JVM or any other tool but Annotation is better way of doing same thing.



Some other Tutorial you may like

18 comments :

Niharika said...

I agree Annotation is better than marker interface in Java. marker interface just contain one information like Serializable, Clonnable etc but with Annotation you can carry more information and it can also server purpose of marker interface in java.

Prasad S N said...

very good explanation, thanks

Daniel Krzywicki said...

One more difference: Annotations can carry more information to the JVM or other tools, but marker interfaces can be used to pass these objects as method arguments - just like with Serializable.

rajalg05 said...

This is the BEST site for interviews

electronics for u said...

Can we create our own marker interface? If we can please explain how to do it.

SARAL SAXENA said...

Javin gr8 article ..!! perfect Expnation..!!

@electronics for u ...yeah we can create our own marker interface...

For example, suppose I declare a new marker interface Foo:

public interface Foo {
}
... and then declare a class Bar that implements Foo:

public class Bar implements Foo {
private final int i;

public Bar(int i) { this.i = i; }
}
I am now able to refer to an instance of Bar through a reference of type Foo:

Foo foo = new Bar(5);
... and also check (at runtime) whether an object implements Foo:

if (o instanceof Foo) {
System.err.println("It's a Foo!");
}
This latter case is typically the driver behind using marker interfaces; the former case offers little benefit as there are no methods that can be called on Foo (without first attempting a downcast)

SARAL SAXENA said...

How JVM invoke this specific behavior
ObjectOutputStream and ObjectInputStream will check your class whether or not it implementes Serializable, Externalizable. If yes it will continue or else will thrown NonSerializableException.

How to write our own marker interface
Create an interface without any method and that is your marker interface.

Sample

public interface IMarkerEntity {


}
If any class which implement this interface will be taken as database entity by your application.

Sample Code:

public boolean save(Object object) throws InvalidEntityException {
if(!(object instanceof IMarkerEntity)) {
throw new InvalidEntityException("Invalid Entity Found, cannot proceed);
}
database.save(object);
}
Is this possible to have methods in marker interface?
The whole idea of Marker Interface Pattern is to provide a mean to say "yes I am something" and then system will proceed with the default process, like when you mark your class as Serialzable it just tells that this class can be converted to bytes.

Javin @ Must Override Eclipse Error said...

@Saral, as always great comment, but I think marker interface is now given way for annotations. Annotations are better way to represent metadata e.g. in place of IMarkerEntity, an annotation @Enttiy, would be much better. Also external tools e.g IDE, compiler, source code checker are making good use of annotations.

Anonymous said...

Another example of marker interface from Java SDK is Remote interface from rmi package. Remote method has no methods, it just used to provide compiler information that a class will be used as remote proxy.

Shekhar said...

Hi guys, How to create our own marker interface in Java? I heard that we can just create an empty interface, that's it but how do we make JVM or Compiler understood there meaning. Suppose I make a marker interface Printable and let a tool can create a print format for that, how to do that in Java?

Rajasekhar Bandaru said...

There are no marker interfaces concepts in JAVA releases. This marker/Tagged interface concepts are popular trough some books/Web, for some understanding these interfaces most commonly no or very less (let us say one) method(s) described in the interface definitions for identifying to provide the special kind of functionality at runtime. Marker interfaces are for identification of a type of class, weather a class is eligible to get some features on runtime of the application or not. The implemented classes will provide the special functionalities on verifying the class type. Let’s take Serializable as an example one, the ObjectOutputStream class will verify before writing the bytes into output streams, weather the received object is of type Serializable or not. Is the object is not implemented serializable then it will throw the exception NotSerializableException.
Now take the another example for marker/tagged interface Cloneable, the clone method of Object’s class is the native method which provides the cloned object when it invoked on any instance which implements Cloneable interface.

naren said...

as per my thinking the compiler just check the
type using instance of and do the specific work.

hence we can also create our own marker interface and do the specific changes when we call that that object.

Anonymous said...

What is the benefit of marker interface, this question was asked in core Java interview at Zensar.

Heta Thakkar said...

nice explanation :) thanks

Anonymous said...

One of the lesser known marker interface in Java is RandomAccess, defined in java.util package. This interface is used to signal that a particular List implementation supports random access to its elements e.g. their get(index) method provides constant time O(1) performance. Main reason, why this marker interface exists is that best algorithms for random access can perform poorly if applied to sequential access list e.g. LinkedList. This interface gives a choice to caller to supply proper algorithm depending upon whether List supports random access or not. On the other hand, any custom List interface implementation, should implement this interface to signal that, they provide get(index) method, which performs better than iterator and it's next() method.

vijay bhatt said...

package com.java.testString;

interface Marker{
}

class MyException extends Exception {
public MyException(String s){
super(s);
}
}

class A {
void m1() throws MyException{
if((this instanceof Marker)){
System.out.println("successfull");
}
else {
throw new MyException("Must implement interface Marker ");
}
}
}

public class CustomMarkerInterfaceExample extends A implements Marker
{ // if this class will not implement Marker, throw exception
public static void main(String[] args) {
CustomMarkerInterfaceExample a= new CustomMarkerInterfaceExample();
try {
a.m1();
} catch (MyException e) {

System.out.println(e);
}


}

}

vijay bhatt said...

interface Marker{
}

class MyException extends Exception {
public MyException(String s){
super(s);
}
}

class A {
void m1() throws MyException{
if((this instanceof Marker)){
System.out.println("successfull");
}
else {
throw new MyException("Must implement interface Marker ");
}
}
}

public class CustomMarkerInterfaceExample extends A implements Marker
{ // if this class will not implement Marker, throw exception
public static void main(String[] args) {
CustomMarkerInterfaceExample a= new CustomMarkerInterfaceExample();
try {
a.m1();
} catch (MyException e) {

System.out.println(e);
}


}

}

Anonymous said...

The designers maybe would have used Annotations instead of the marker interfaces Serializable or Cloneable, but these marker interfaces belong to Java 1.0 and there was no annotation concept back then. Annotations were introduced in Java 1.5.

Post a Comment