Skip to content

Latest commit

 

History

History
94 lines (68 loc) · 2.86 KB

File metadata and controls

94 lines (68 loc) · 2.86 KB

Q14 — Marker Interface

Interview Tip: Simple concept — nail the "why no methods?" explanation and the modern alternative (annotations) to stand out.


🔑 What is a Marker Interface?

An interface with no methods and no fields — it just "marks" a class to signal something to the JVM or framework.

public interface Serializable {
    // empty — no methods
}

📌 Built-in Marker Interfaces

Interface Package What it signals
Serializable java.io Object can be serialized
Cloneable java.lang Object can be cloned via clone()
Remote java.rmi Object can be used in RMI (Remote Method Invocation)
RandomAccess java.util List supports fast random access (e.g., ArrayList)

💻 Code — Demo Cloneable

// Without Cloneable — throws CloneNotSupportedException
class Car implements Cloneable {
    String brand;
    int year;

    Car(String brand, int year) {
        this.brand = brand;
        this.year = year;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();  // JVM checks if Cloneable is implemented
    }
}

public class MarkerInterfaceDemo {
    public static void main(String[] args) throws Exception {
        Car car1 = new Car("Toyota", 2022);
        Car car2 = (Car) car1.clone();

        System.out.println(car1.brand);  // Toyota
        System.out.println(car2.brand);  // Toyota
        System.out.println(car1 == car2); // false — different objects

        // If Car didn't implement Cloneable:
        // → clone() throws CloneNotSupportedException at runtime
    }
}

📌 How JVM Uses Marker Interfaces

  • SerializableObjectOutputStream.writeObject() checks instanceof Serializable before serializing
  • CloneableObject.clone() checks instanceof Cloneable before allowing clone
  • If class doesn't implement → runtime exception thrown

📌 Marker Interface vs Annotation (Modern Alternative)

Marker Interface Annotation
Example implements Serializable @Serializable
Type checking instanceof at runtime Reflection
Can add metadata ❌ No ✅ Yes (@Retention, @Target)
Modern usage Legacy code Preferred in modern Java

Java annotations like @Override, @FunctionalInterface, @Deprecated have replaced most marker interface use cases in modern code.


📌 Key Points

  • Marker interface = empty interface, no methods
  • Purpose: signal/tag a class for special treatment by JVM or framework
  • Serializable and Cloneable are the most common examples in interviews
  • JVM checks marker interface via instanceof at runtime
  • Modern Java prefers annotations over marker interfaces
  • You can create your own marker interface — but use annotation instead in new code