Nani
Nani

Reputation: 363

Why do we implement marker Interface even if they doesn't contain any methods?

I have been thinking about this but couldn't discard it right away, why we will even implement Marker Interfaces to our class if even though they doesn't contain any methods. Please let me know

Upvotes: 1

Views: 698

Answers (4)

Narendra Pathai
Narendra Pathai

Reputation: 41945

Marker interfaces as the name suggest are used for just an indication and they mark the class implementing that interface.

Now in your code you can take some actions on it like (instance instanceof Marker)

At most places Annotations can be used for Markers

For example if @Test on a class shows that this class is a Test class and should be executed. Same can be achieved with an interface.

@Test //sort of marking
class ClassToTest{

}

or

class ClassToTest implements Test{

}

The above examples are synonymous in the way what they are trying to achieve.

For checking the presence in the first case you will try to check the presence of @Test annotation and in second case you will make instanceof check.

With marker interfaces you also get an advantage that if you store all the instances of test, then you can have a type safe collection List<Test> or if you want to make a type safe method that will only accept the instances of Test

void method(Test testInstance){

}

Upvotes: 3

Mudit Shukla
Mudit Shukla

Reputation: 894

Marker interface is used as a tag to inform a message to the java compiler so that it can add special behavior to the class implementing it.

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.

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 691755

Let's take an example: Serializable.

If you try to serialize an object, the Java serialization mechanism will throw an exception if your object is not an instance of Serializable. To make it an instance of Serializable, the class of the object thus has to implement the Serializable interface, even if that interface doesn't contain any method. Just so that

o instanceof Serializable

is true, rather than false.

Upvotes: 3

lidl
lidl

Reputation: 49

For the invoker. just like : Interface A,the implement B. usually A is invoked.In spring framework,it is familiar

Upvotes: 0

Related Questions