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

Serialization and Inheritance

Learning how serialization works when superclasses do or do not implement Serializable.

Serialization and Inheritance

You'll learn how serialization behaves when a class hierarchy involves both serializable and non-serializable classes.

The Core Idea

When you serialize an object, you're not just dealing with one class—you're dealing with an entire inheritance chain. Java needs to know: should it serialize fields from the superclass too? The answer depends on whether the superclass implements Serializable.

Here's how it works:

If the superclass implements Serializable: All inherited fields (from that superclass and above) are automatically serialized along with the subclass fields. The entire object graph is preserved.

If the superclass does NOT implement Serializable: Java cannot serialize the superclass fields. During deserialization, Java will call the no-argument constructor of the first non-serializable superclass to initialize those fields—meaning the superclass fields get default-initialized values, not the serialized values.

The Analogy

Think of serialization like packing a family photo album. If your parents (superclass) agreed to be photographed (Serializable), their pictures get included with yours. But if they opted out (no Serializable), you can only pack your own photos. When the album is unpacked elsewhere, a generic placeholder appears where their photos should be—created from scratch, not from the original.

What This Means in Practice

If you make a subclass serializable but the superclass isn't:

  • The subclass fields serialize normally
  • The superclass must have a no-argument constructor (or Java throws an exception)
  • After deserialization, superclass fields contain default values (0, null, false, etc.), not their original values

Key Takeaway: Serialization flows down the inheritance hierarchy—superclass fields are only serialized if the superclass implements Serializable; otherwise, they're reinitialized via the superclass's no-argument constructor during deserialization.