Serialization: Freezing Objects

Serialization: Freezing Objects in Java: Imagine you are playing a video game. When you click Save Game, the computer needs to take your character's level,…

Concept Explanation

Imagine you are playing a video game. When you click Save Game, the computer needs to take your character's level, health, and position and "freeze" them into a file so you can load them later.

In Java, this "Freezing" is called Serialization. "Unfreezing" it back into an object is called Deserialization.


Syntax or Core Structure

1. Marking the Class

The class MUST implement the Serializable interface. This tells Java, "It's safe to turn this into bytes."

import java.io.Serializable;

class Player implements Serializable {
    String name;
    int level;
    // transient means "Don't save this"
    transient String password; 
}

2. Saving (Serializing)

Player p = new Player("Hero", 10);
try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("save.dat"))) {
    out.writeObject(p);
}

Common Mistakes

  • Missing Interface: If your class doesn't implement Serializable, you'll get a NotSerializableException.
  • SerialVersionUID: If you change your class (add a field) after saving, Java might refuse to load the old file unless you define a serialVersionUID.

Practice Exercises

  1. The Frozen Student: Create a Student class with name and GPA. Serialize it to a file named "student.ser".
  2. The Secret Field: Add a transient field to a class. Serialize it, then deserialize it. What is the value of that field after loading?
  3. Multiple Objects: Research how to save an ArrayList of objects to a single file using ObjectOutputStream.