Serialization and Object Graphs
What you'll learn: How serialization automatically follows object references to save entire networks of connected objects.
The Chain Reaction of Serialization
When you serialize an object, Java doesn't just save that single object in isolation. Instead, it automatically follows every reference that object contains and serializes those objects too—and their references, and so on. This connected network of objects is called an object graph.
Think of it like packing for a trip: if you pack your laptop bag, you're also packing everything inside it—the laptop, charger, mouse, and any other items stored in the pockets. You don't pack each item separately; they come along as a complete set.
How It Works
When ObjectOutputStream serializes an object:
- It writes the object's class information and field values
- For each field that's an object reference (not a primitive), it recursively serializes that referenced object
- It continues following references until it has captured the entire graph
- Java tracks which objects it has already serialized to handle circular references (object A references B, B references A)
What Gets Included
If your Person object has an Address field, and Address has a Country field, serializing the Person automatically serializes the Address and Country too—provided all these classes implement Serializable.
This means you can serialize complex data structures with a single writeObject() call. However, it also means every reachable object must be serializable, or you'll get a NotSerializableException.
Key Takeaway: Serialization automatically traverses and saves entire object graphs by following all object references, not just the top-level object you explicitly serialize.