Making a Class Serializable
What You'll Learn
You'll learn the exact syntax for enabling a Java class to be serialized by implementing the Serializable marker interface.
The Core Idea
To make a class serializable in Java, you simply add implements Serializable to your class declaration. That's it! This tiny addition tells Java that objects of this class can be converted into a byte stream (for saving to disk, sending over a network, etc.).
Here's the basic syntax:
import java.io.Serializable;
public class Person implements Serializable {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
Notice three things:
- You must import
java.io.Serializable - Add
implements Serializableafter the class name (just like implementing any interface) - You don't need to implement any methods—
Serializableis a marker interface with no methods to override
Why This Works
Think of Serializable as a permission slip you give to Java. By implementing this interface, you're saying: "Yes, I give Java permission to inspect my object's fields and convert them to bytes." Without this explicit permission, Java refuses to serialize your object and will throw a NotSerializableException.
Any class whose objects you want to save, send, or store outside of memory needs this one-line addition. All the fields in your class (String, int, etc.) must themselves be serializable—but Java's built-in types already are.
Key Takeaway: Making a class serializable requires only adding implements Serializable to the class declaration—no methods to implement, just explicit permission for Java to serialize your objects.