The marker interface in Java interfaces with no field or methods or, in simple words empty interface in java is called a marker interface. Example of marker interface is Serializable, Cloneable, and Remote interface. If the marker interface doesn't have any field or method, or behavior, why would Java need it? This was asked to one of my friends in one of his core java interviews, and then I thought to touch base on it. In this article, we will see a couple of reasons for what marker interfaces do in Java and the use of marker interfaces in Java. A marker interface is also called a tag interface in Java.
What is Marker interfaces in Java, and why required
Now, let's understand the marker interface in Java, some common examples of marker interfaces, and what benefits they provide.1. What Marker or Tag interface do in Java?
Looking carefully at marker interfaces in Java, like, Serializable, Cloneable, and Remote, it looks they are used to indicate something to compiler or JVM. So if JVM sees a Class is Serializable, it has done some special operation on it, a similar way, if JVM sees one Class is implement Cloneable, it performs some operation to support cloning.
The same is true for RMI and Remote interface. So, in short, the Marker interface indicates a signal or a command to Compiler or JVM.
And, If you are new to the Java world, then I also recommend you go through these Java programming courses to learn Java in a better and more structured way. This is one of the best and up-to-date courses to learn Java online.
The same is true for RMI and Remote interface. So, in short, the Marker interface indicates a signal or a command to Compiler or JVM.
And, If you are new to the Java world, then I also recommend you go through these Java programming courses to learn Java in a better and more structured way. This is one of the best and up-to-date courses to learn Java online.
This is a pretty standard answer to the question about the marker interface. 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 makes sense, right?
Yes, this can also be done by using a boolean flag or a String. Still, it doesn't mark a class like Serializable or Cloneable, makes it more readable, and it also allows one to take advantage of Polymorphism in Java.
Where Should I use the Marker interface in Java?
Apart from using a built-in marker interface for making a class Serializable or Cloneable. One can also develop his own marker interface. The marker interface is a good way to classify code.
You can create a marker interface to logically divide your code and if you have your own tool, you can perform some preprocessing operations on those classes. Particularly useful for developing API and frameworks like Spring or Struts.
After introducing Annotation on Java 5, Annotation is a better choice than the marker interface, and JUnit is a perfect example of using Annotation, e.g., @Test, for specifying a Test Class. The same can also be achieved by using a 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 ThreadSafe can communicate to other developers that classes implementing this marker interface give a thread-safe guarantee, and any modification should not violate that.
The marker interface can also help code coverage or a code review tool to find bugs based on specified behavior of marker interfaces.
Again Annotations are a better choice @ThreadSafe looks a lot better than implementing the ThreadSafe marker interface.
In summary, the marker interface in Java is used to indicate something to the compiler, JVM, or any other tool, but Annotation is a better way of doing the same thing.
Some other Java Tutorial you may like
If you have been asked this question on Interview then please let us know in comments and if you have anything to add, feel free to drop a note, I will add on the article with your name. I also appreciate your contribution.
38 comments :
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.
very good explanation, thanks
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.
This is the BEST site for interviews
Can we create our own marker interface? If we can please explain how to do it.
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)
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.
@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.
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.
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?
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.
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.
What is the benefit of marker interface, this question was asked in core Java interview at Zensar.
nice explanation :) thanks
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.
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);
}
}
}
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);
}
}
}
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.
This is the BEST site for interview
Read some of the reasons why James Gosling created interfaces. you need to understand Java, not just know it.
The main purpose of marker interfaces is to create special types where types themselves have no behavior of their own.
public interface MarkerEntity {
}
public boolean save(Object object) throws InvalidEntityFoundException {
if(!(object instanceof MarkerEntity)) {
throw new InvalidEntityFoundException("Invalid Entity Found, can't be saved);
}
return db.save(object);
}
Here save method makes sure that only the objects of classes that implement the MarkerEntity interface are saved, for other types InvalidEntityFoundException is thrown. So here MarkerEntity marker interface is defining a type that adds special behavior to the classes implementing it.
Though annotations can also used now to mark classes for some special treatments but marker annotations are replacement for naming pattern not for Marker interfaces.
But marker annotations can't fully replace the marker interfaces because; marker interfaces are used to define type (as already explained above) where as marker annotations do not.
Everyone saying Marker interface is designed in such a way that JVM get notified when one class implement that Marker interface.Now i am really curious to know how JVM is designed that it came to know that this is special type of interface.
Why to use marker interface.? If its use is restricted just to be used as an indication to JVM then we can have a flag in Object class. This way all classes will have this flag.
Hi Every One! Marker Interface means it has no methods in that. right ? so this is not correct definition for marker interface. Marker Interface is an Interface which is gives ability, functionality to derived classes. Like Runnable Interface it has run() method and Serializable no method, Cloneable no method too.
Superb Article . Very Nicely Explained :)
A marker interface does not indicate anything to compiler or JVM. It indicates java classes to implement it in a different way from other interfaces. Please go through this link for a better understanding.
http://stackoverflow.com/questions/20869993/why-does-arraylist-implement-randomaccess-interface
Good artical ,and the comments are also awesome .
if any interface doesn't contain any method and by implemeting this interface if our object will get some ability then such type of interface is called marker interface.
Hi.. can marker interface have some methods????
Because I have read somewhere saying marker interface can have .
This post is correct in the parts that (1) a marker interface must be empty, and (2) implementing it is meant to imply some special treatment of the implementing class. The part that is incorrect is that it implies that JVM or the compiler would treat the objects of that class differently. In fact, it's the code of Java class library that treats these objects as cloneable, serializable, etc. It has nothing to do with the compiler or the JVM.
Hello @Unknown, The default Serialization is implemented ad compiler and JVM level which uses marker interface, isn't it? The purpose of marker interface is same as annotation, to indicate something, now the tool which could use this information can be anything e.g. another Java program like ant or compiler or JVM etc.
market interface
It’s a kind of interface which has no method is known as marker interface. Serializable, Clonnable is the example of marker interface to Marker Interface in Java
Use of Marker Interface:
Marker Interfaces are used to indicate something to compiler/JVM. If JVM see that a class is a object of Marker Interface then it will perform some special operation. Take an example with Serializable, Clonnable marker interface, if JVM see a Class is Serialized/Clonnable then It will do some special operation on it, similar way if JVM sees one Class is implemented custom marker interface which is created by ourself then the JVM do some special operation.
It is marker interface, not "market interface" .
It is marker interface, not "market interface" .
Another good question on this, which was asked to me in one of the interview was that can you create your own marker classes, and answer is yes we can, as the marker classes are just to mark the classes so that compiler knows what it means, if we create a interface of our own say example CustomCheckMarker, we can check at run time classes that implement this interface and can do some custom checking before doing some operations.
Hello Nikhil, thanks for adding value but I would also highlight one aspect of marker interface that if he means to something inside JVM then it's not possible. For example, JVM or Compiler does special things for Serializable, it's not possible for custom marker interface to achieve same because you can't modify JVM code. But, logically your answer is correct.
To me, Marker interface looks like completely useless, this can be easily done by using an Annotation? what do you guys think? I am really curious to know the true purpose and significance of Marker interface? If anyone knows what is the role of Marker interface in Java then do comment? I know from this article that Marker interface is kind of hint or suggestion but why not use Annotation instead of Marker interface?
Post a Comment