What is a Marker Interface in Java - DevDummy

Latest

Views | Thoughts | Concepts | Techniques

Thursday, September 07, 2017

What is a Marker Interface in Java

What is a marker interface ?
Interface which does not contain any method to implement are called marker or the tag interfaces. 

Why marker interfaces ?
The basic idea of having marker interfaces are to mention that the class is implementing an interface of which, the behavior is implicit.  
The class is not expected to implement anything to adhere to the contract defined by the interface. In contrast it is to indicate the JVM regarding an expected functionality to perform implicitly.

Java Example
  • Serializable - Eligible to serialize this type of objects
  • Remote - This type is eligible remote method calls
  • Clonnable - Eligible to make a field-for-field copy of instances
Can we create custom marker interfaces ?
Yes, It is possible. However is is not possible to write similar to Serializable interface . But we can simulate the functionality by coding it in the marker interface.

What are the uses of custom marker interfaces ?
  • Categorize or group specific classes in to manageable sets
  • Indicate the API users to follow specific rules in the implementations which can not be defined as contracts. Example : Async/ Thread Safe
  • Define internal tasks which are needed to be done by the JVM implicitly.

References

No comments:

Post a Comment