Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use of marker interfaces in Java?

When there is nothing to implement in the marker interfaces like Serializable What is the use of implementing it?

like image 650
GuruKulki Avatar asked Jan 03 '10 15:01

GuruKulki


People also ask

Why do we use marker interface in Java?

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

What is marker interface in Java and examples?

It is an empty interface (no field or methods). Examples of marker interface are Serializable, Cloneable and Remote interface. All these interfaces are empty interfaces.

What is the use of marker annotation?

Category 1: Marker Annotations The only purpose is to mark a declaration. These annotations contain no members and do not consist of any data. Thus, its presence as an annotation is sufficient. Since the marker interface contains no members, simply determining whether it is present or absent is sufficient.

How many marker interfaces are available in Java?

It has three types: Serializable interface. Cloneable interface. Remote interface.


2 Answers

Joshua Bloch: Effective Java 2nd Edition, p 179

Item 37: Use marker interfaces to define types

... You may hear it said that marker annotations (Item 35) make marker interfaces obsolete. This assertion is incorrect. Marker interfaces have two advantages over marker annotations. First and foremost, marker interfaces define a type that is implemented by instances of the marked class; marker annotations do not. The existence of this type allows you to catch errors at compile time that you couldn’t catch until runtime if you used a marker annotation....

Personally I think I'll bow to Joshua's superior knowledge on this subject.

like image 180
T C Avatar answered Sep 22 '22 18:09

T C


In earlier versions of Java, Marker Interfaces were the only way to declare metadata about a class. For example, the Serializable Marker Interface lets the author of a class say that their class will behave correctly when serialized and deserialized.

In modern Java, marker interfaces have no place. They can be completely replaced by Annotations, which allow for a very flexible metadata capability. If you have information about a class, and that information never changes, then annotations are a very useful way to represent it.

like image 30
Chris Pitman Avatar answered Sep 19 '22 18:09

Chris Pitman