Marker Interface example in Java

The marker interface pattern is a design pattern that provide run-time type information about objects. It provides a means to associate metadata with a class when there is no explicit support for such metadata.

Marker interfaces in Java, e.g. Serializable, Clonnable and Remote, are used to indicate something to compiler or JVM. So if JVM finds a Class is Serializable it does some special operation on it, similar way if JVM finds a Class is implementing Clonnable it performs some operation to support cloning. Marker interface indicates a signal or a command to Compiler or JVM.
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.

One more use of marker interface in Java can be commenting. A 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.

Let’s take an Example

Create a BankDraft interface

 

Create a Cheque interface

 

Class Payment implements Cheque interface

 

Now test it

 

Output :

 

Now Payment implements BankDraft

 

Now test it

 

Output :

 

Soumitra

Software Professional, I am passionate to work on web/enterprise application. For more information please go to about me. You can follow on Twitter. You can be a friend on Facebook or Google Plus or Linkedin

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.