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 aNotSerializableException. - 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
- The Frozen Student: Create a
Studentclass with name and GPA. Serialize it to a file named "student.ser". - The Secret Field: Add a
transientfield to a class. Serialize it, then deserialize it. What is the value of that field after loading? - Multiple Objects: Research how to save an
ArrayListof objects to a single file usingObjectOutputStream.