๐ŸŽ‰ Special Offer !    Code: GET300OFF    Flat โ‚น300 OFF on every Java Course
Grab Deal ๐Ÿš€

Marker Interfaces  


Introduction
  • A Marker Interface is an interface that has no methods and no fields.
  • It is used to "mark" a class, giving a special meaning or behavior to the class which implements it.
  • The Java compiler and JVM use this marker to decide how to treat objects of that class.
  • Examples of marker interfaces in Java:
    • java.io.Serializable
    • java.lang.Cloneable
    • java.util.RandomAccess
  • Key Points:
    • There are no abstract methods in a marker interface.
    • They serve as a metadata tag that can be checked at runtime using instanceof operator or reflection.
    • The real work is done by JVM or API classes that check whether the object is marked with that interface.
Uses of Marker Interfaces
  • To give permission to a class for some special operation.
    • Example: A class must implement Serializable to be eligible for object serialization.
  • To request special behavior from JVM or libraries.
    • Example: If a class implements Cloneable, then Object.clone() method will perform cloning, otherwise it throws CloneNotSupportedException.
  • To group classes logically for a specific purpose.
Program:
  • Program 1: Example of a Marker Interface:
    // Marker Interface
    interface Marker { }
    
    // Class implementing Marker
    class MyClass implements Marker
    {
        public void display()
        {
            System.out.println("Display method called");
        }
    }
    
    public class MainApp
    {
        public static void main(String[] args)
        {
            MyClass obj = new MyClass();
    
            if (obj instanceof Marker) {
                obj.display();
            } else {
                System.out.println("Object not allowed");
            }
        }
    }