Serializable

⭐ Interview Importance: MEDIUM
⏱️ Revision Time: 5 min

TL;DR

  • java.io.Serializable is a Marker Interface.
  • It contains no methods whatsoever.
  • It acts purely as a flag to give the JVM permission to serialize the class. If you try to serialize a class without this interface, a NotSerializableException is thrown.

Concept

Why didn’t the Java designers just make every class serializable by default?
Because serialization is dangerous. It exposes the private internal state of an object to the outside world. It also bypasses constructors upon deserialization.

If a DatabaseConnection class was serializable, someone could serialize it, send it over the network, and deserialize it on a different machine, resulting in a completely broken object (since the physical socket connection doesn’t exist on the new machine).

The Serializable interface is an opt-in mechanism. By declaring implements Serializable, the developer is explicitly telling the JVM: “I have thought about the implications, and I permit you to convert this object’s internal state into bytes.”

Examples

import java.io.Serializable;

// 1. A Marker Interface has absolutely no methods to implement.
public class GameSaveState implements Serializable {
    
    // We highly recommend declaring this ID (explained in the next topic)
    private static final long serialVersionUID = 1L;
    
    private int playerLevel;
    private int playerHealth;
    
    public GameSaveState(int level, int health) {
        this.playerLevel = level;
        this.playerHealth = health;
    }
}

Interview Questions

Q: What is a Marker Interface?
A: A Marker Interface (like Serializable, Cloneable, or Remote) is an interface that contains zero methods or fields. Its sole purpose is to “tag” a class so that the JVM, the compiler, or a framework can check for its presence (using instanceof or Reflection) and provide special internal behavior. Note: In modern Java, Marker Interfaces are largely considered an anti-pattern, having been replaced by standard Annotations (e.g., @Serializable).

Q: If a class implements Serializable, do all its subclasses automatically become serializable?
A: Yes. Inheritance applies to interfaces. If class Animal implements Serializable, then class Dog extends Animal is automatically serializable, whether you explicitly declare it on the Dog class or not. If you want to prevent a subclass from being serialized, you must override the special writeObject() method and throw a NotSerializableException.