Course contentsShow
← Java
Lesson 2110 of 2,87042. SerializationFree lesson

Serialization and Object Graphs

Understanding that serialization follows object references, serializing entire object graphs automatically.

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:

  1. It writes the object's class information and field values
  2. For each field that's an object reference (not a primitive), it recursively serializes that referenced object
  3. It continues following references until it has captured the entire graph
  4. 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.