Java Marker Interface: Defining Special Behavior

A Marker Interface 👇 A Marker Interface in Java is an interface that contains no methods or fields. It is used to mark a class so that the Java runtime or compiler can identify some special behavior or capability of that class. Example: Here, Serializable has no methods but if a class implements it, Java knows that objects of that class can be serialized. 🔹A Marker Interface (also known as a Tagging Interface) is a design pattern in Java where an interface contains no methods or constants. If you look at the source code of a marker interface, it’s just an empty shell: Java public interface MyMarkerInterface { // Absolutely nothing here } Why use an empty interface? The purpose isn't to define behavior (like a normal interface does), but to deliver a message to the JVM or a framework. It acts like a "stamp" or a "label" on a class. When a class implements a marker interface, it's telling the runtime: "I have a special property. You can treat me differently." 🌟 How It Works (The "Metadata" Approach) Since the interface is empty, the class implementing it doesn't have to write any new code. Instead, other parts of the system use the instanceof operator to check for the "stamp." 🔹The Logic: Class A implements Serializable. ✔ The JVM sees a request to save Class A to a file. ✔ The JVM checks: if (A instanceof Serializable). ✔ If True: The JVM proceeds with the specialized logic to save the data. ✔ If False: The JVM throws a NotSerializableException. Famous Examples in Java  🔹 Serializable: Tells the JVM that the object’s state can be converted into a byte stream (saved to a file or sent over a network). 🔹Cloneable: Tells the Object.clone() method that it is legal to make a field-for-field copy of instances of that class. 🔹Remote: Used in RMI (Remote Method Invocation) to identify interfaces whose methods may be invoked from a non-local virtual machine. I’m truly thankful to my mentor for their valuable guidance Anand Kumar Buddarapu Saketh Kallepu Uppugundla Sairam #Java #CoreJava #MarkerInterface #JavaProgramming #OOP #Serializable #Cloneable #JavaConcepts #Programming #Developers

  • graphical user interface, text, application

To view or add a comment, sign in

Explore content categories