Skip to lesson

Object graphs and NotSerializableException

An object graph is an object together with every object it refers to, and every object those refer to, and so on. When you serialize one object, Java walks this whole graph and saves all of it.

Nested objects and collections are saved too

When writeObject(room) saves a Room, it also saves every object in the room's fields: its List, each Resident in the list, and each resident's Address. This is the object graph, and Java saves it all from that one call.

Example 1 · One writeObject saves the whole hostel room

HostelGraphDemo.javaJava
import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.io.Serializable;import java.util.ArrayList;import java.util.List;
class Address implements Serializable {    String city;    String pin;
    Address(String city, String pin) {        this.city = city;        this.pin = pin;    }}
class Resident implements Serializable {    String name;    Address home;          // a nested object
    Resident(String name, Address home) {        this.name = name;        this.home = home;    }}
class Room implements Serializable {    String number;    List<Resident> residents = new ArrayList<>();   // a collection of objects
    Room(String number) {        this.number = number;    }}
public class HostelGraphDemo {    static byte[] toBytes(Object obj) throws IOException {        ByteArrayOutputStream buffer = new ByteArrayOutputStream();        try (ObjectOutputStream out = new ObjectOutputStream(buffer)) {            out.writeObject(obj);        }        return buffer.toByteArray();    }
    static Object fromBytes(byte[] bytes) throws IOException, ClassNotFoundException {        try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes))) {            return in.readObject();        }    }
    public static void main(String[] args) throws IOException, ClassNotFoundException {        Room room = new Room("B-204");        room.residents.add(new Resident("Ravi", new Address("Nagpur", "440001")));        room.residents.add(new Resident("Sameer", new Address("Kochi", "682001")));
        Room copy = (Room) fromBytes(toBytes(room));   // only the Room is passed in
        System.out.println("Room " + copy.number + " has " + copy.residents.size() + " residents");        for (Resident r : copy.residents) {            System.out.println("  " + r.name + " from " + r.home.city + " " + r.home.pin);        }    }}
Output
Room B-204 has 2 residents
  Ravi from Nagpur 440001
  Sameer from Kochi 682001

What this code does

  • Only room is passed to toBytes, but the list, both residents and both addresses are saved too because they are reachable from it.
  • One fromBytes call rebuilds the full graph, so copy.residents.get(0).home.city works straight away.
  • toBytes and fromBytes serialize to memory with ByteArrayOutputStream and ByteArrayInputStream.

On the way back, one readObject() rebuilds the full graph. You get the room with its list, the residents and their addresses, all connected the same way as before. The common JDK classes you use for data are serializable: String, the wrapper classes such as Integer, arrays, ArrayList, HashMap, TreeMap, and the lists from List.of. Your own classes in the graph need implements Serializable.

Example 1 adds two small helpers, toBytes and fromBytes, that serialize to memory. Later examples use the same idea so the code stays short.

NotSerializableException and its message

NotSerializableException is thrown by writeObject when an object in the graph belongs to a class that does not implement Serializable. Its message is the name of that class.

NotSerializableException is thrown when any object in the graph has a class that is not Serializable, not only the object you passed to writeObject. The message is the name of that class, which tells you exactly what to fix.

Example 2 · A non-serializable field breaks the save

NestedFailDemo.javaJava
import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.NotSerializableException;import java.io.ObjectOutputStream;import java.io.Serializable;
class Customer {                       // forgot implements Serializable    String phone;
    Customer(String phone) {        this.phone = phone;    }}
class OnlineOrder implements Serializable {    int orderId;    Customer customer;
    OnlineOrder(int orderId, Customer customer) {        this.orderId = orderId;        this.customer = customer;    }}
public class NestedFailDemo {    public static void main(String[] args) throws IOException {        OnlineOrder order = new OnlineOrder(501, new Customer("98450xxxxx"));        try (ObjectOutputStream out = new ObjectOutputStream(new ByteArrayOutputStream())) {            out.writeObject(order);            System.out.println("Saved");        } catch (NotSerializableException e) {            System.out.println("Could not save: " + e.getMessage());        }
        OnlineOrder noCustomer = new OnlineOrder(502, null);        try (ObjectOutputStream out = new ObjectOutputStream(new ByteArrayOutputStream())) {            out.writeObject(noCustomer);            System.out.println("Order 502 saved (customer is null)");        }    }}
Output
Could not save: Customer
Order 502 saved (customer is null)

What this code does

  • OnlineOrder is serializable, but its Customer is not, so writeObject throws NotSerializableException with the message Customer.
  • Order 502 has customer = null. A null field is written as "null", so this order saves without any error.

What to fix depends on the class:

  • Your own classes: add implements Serializable.
  • Things that cannot be saved, such as an open file stream, a Thread or a database connection: do not keep them in the saved fields.
  • A list is serializable only when every element in it is.

So if OnlineOrder is serializable but its customer field holds a Customer that is not, saving the order fails with the message Customer. The fix is to add implements Serializable to Customer, or to stop saving that field (the next lesson shows how). A null field is fine: there is no object to save, so Java just writes "null". The error appears only when a real object of the wrong class is in the graph.

Fix the error

Fix NotSerializableException

Read the real error, then pick the line that fixes it.

Round 1 of 2

An order holds a customer, and saving the order fails.

class Customer {
String name = "Ravi";
}
class Order implements Serializable {
Customer customer = new Customer();
}

Error

Exception in thread "main" java.io.NotSerializableException: Customer
	at java.base/java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1198)

Shared references are written once

If two objects point to the same third object, Java writes that object only once. The second time, it writes a short back-reference: a note that says "the object written earlier". After reading, both objects again point to one shared object, not to two copies.

Example 3 · Shared mentor and a cycle survive the round trip

SharedMentorDemo.javaJava
import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.io.Serializable;import java.util.ArrayList;import java.util.List;
class Mentor implements Serializable {    String name;    List<Learner> learners = new ArrayList<>();   // points back to the learners
    Mentor(String name) {        this.name = name;    }}
class Learner implements Serializable {    String name;    Mentor mentor;
    Learner(String name, Mentor mentor) {        this.name = name;        this.mentor = mentor;        mentor.learners.add(this);    }}
public class SharedMentorDemo {    public static void main(String[] args) throws IOException, ClassNotFoundException {        Mentor m = new Mentor("Dr. Rao");        Learner a = new Learner("Anu", m);        Learner b = new Learner("Bilal", m);
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();        try (ObjectOutputStream out = new ObjectOutputStream(buffer)) {            out.writeObject(a);            out.writeObject(b);        }
        try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray()))) {            Learner a2 = (Learner) in.readObject();            Learner b2 = (Learner) in.readObject();
            System.out.println("Same mentor object? " + (a2.mentor == b2.mentor));            System.out.println("Mentor's learners: " + a2.mentor.learners.size());            System.out.println("Cycle kept? " + (a2.mentor.learners.get(0) == a2));
            a2.mentor.name = "Dr. Rao (HOD)";            System.out.println("Bilal's mentor: " + b2.mentor.name);        }    }}
Output
Same mentor object? true
Mentor's learners: 2
Cycle kept? true
Bilal's mentor: Dr. Rao (HOD)

What this code does

  • Both learners point to the same Mentor. Java writes it once, so after reading, a2.mentor == b2.mentor is true.
  • The mentor's list points back to the learners. Java handles this cycle, and the first learner in the list is the same object as a2.
  • Changing the name through a2.mentor is seen through b2.mentor, because there is one shared object.

Example 4 · Trap: writing a changed object again on the same stream

WriteTwiceDemo.javaJava
import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.io.Serializable;
class LiveScore implements Serializable {    int runs;
    LiveScore(int runs) {        this.runs = runs;    }}
public class WriteTwiceDemo {    static void sendTwice(boolean reset) throws IOException, ClassNotFoundException {        LiveScore score = new LiveScore(120);        ByteArrayOutputStream buffer = new ByteArrayOutputStream();        try (ObjectOutputStream out = new ObjectOutputStream(buffer)) {            out.writeObject(score);      // first update: 120            score.runs = 134;            if (reset) {                out.reset();             // forget the objects already written            }            out.writeObject(score);      // second update: 134?        }        try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray()))) {            LiveScore first = (LiveScore) in.readObject();            LiveScore second = (LiveScore) in.readObject();            System.out.println("reset=" + reset + ": " + first.runs + ", " + second.runs                    + " (same object: " + (first == second) + ")");        }    }
    public static void main(String[] args) throws IOException, ClassNotFoundException {        sendTwice(false);        sendTwice(true);    }}
Output
reset=false: 120, 120 (same object: true)
reset=true: 120, 134 (same object: false)

What this code does

  • Without reset, the second writeObject(score) writes only a back-reference. The reader gets the same object twice, still with 120 runs.
  • out.reset() makes the stream forget earlier objects, so the second write saves a fresh copy with 134 runs.

The same rule makes cycles work. A cycle is when objects point back to each other, like a mentor who knows the learners and learners who know the mentor. Java does not loop forever; it writes each object once. The rule has a trap. An ObjectOutputStream remembers every object it has written. If you change an object and write it again on the same stream, Java writes only a back-reference, so the reader gets the old values. Call out.reset() before writing it again to make the stream forget.

Back-references work inside one stream. Two separate writeObject calls on two different streams give two separate copies.

Inheritance and serializable parents

A subclass of a Serializable class is serializable too; it does not need to repeat implements Serializable. Fields from every serializable class in the chain are saved.

Example 5 · A non-serializable parent loses its fields

ParentFieldsDemo.javaJava
import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.io.Serializable;
class Person {                                  // NOT Serializable    String name;
    Person() {        System.out.println("  Person() runs");        name = "unknown";    }
    Person(String name) {        this.name = name;    }}
class CollegeStudent extends Person implements Serializable {    int roll;
    CollegeStudent(String name, int roll) {        super(name);        this.roll = roll;    }}
class Staff implements Serializable {           // parent of Professor    String name;
    Staff(String name) {        this.name = name;    }}
class Professor extends Staff {                 // Serializable through Staff    String subject;
    Professor(String name, String subject) {        super(name);        this.subject = subject;    }}
public class ParentFieldsDemo {    static Object copy(Object obj) throws IOException, ClassNotFoundException {        ByteArrayOutputStream buffer = new ByteArrayOutputStream();        try (ObjectOutputStream out = new ObjectOutputStream(buffer)) {            out.writeObject(obj);        }        try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray()))) {            return in.readObject();        }    }
    public static void main(String[] args) throws IOException, ClassNotFoundException {        System.out.println("Reading a CollegeStudent:");        CollegeStudent s = (CollegeStudent) copy(new CollegeStudent("Divya", 31));        System.out.println("  name=" + s.name + ", roll=" + s.roll);
        System.out.println("Reading a Professor:");        Professor p = (Professor) copy(new Professor("Dr. Iyer", "Physics"));        System.out.println("  name=" + p.name + ", subject=" + p.subject);        System.out.println("Professor is Serializable? " + (p instanceof Serializable));    }}
Output
Reading a CollegeStudent:
  Person() runs
  name=unknown, roll=31
Reading a Professor:
  name=Dr. Iyer, subject=Physics
Professor is Serializable? true

What this code does

  • Person is not serializable, so its name is not saved. On reading, Java runs Person(), which sets the name to "unknown".
  • Staff is serializable, so Professor is serializable too without saying so, and both name and subject come back.
  • Note that CollegeStudent's own constructor does not run during reading; only the non-serializable parent's no-argument constructor does.

Example 6 · Mistake: the parent has no no-argument constructor

NoValidConstructorDemo.javaJava
import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InvalidClassException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.io.Serializable;
class Account {                          // NOT Serializable, and no no-arg constructor    String holder;
    Account(String holder) {        this.holder = holder;    }}
class SavingsAccount extends Account implements Serializable {    int balance;
    SavingsAccount(String holder, int balance) {        super(holder);        this.balance = balance;    }}
public class NoValidConstructorDemo {    public static void main(String[] args) throws IOException, ClassNotFoundException {        ByteArrayOutputStream buffer = new ByteArrayOutputStream();        try (ObjectOutputStream out = new ObjectOutputStream(buffer)) {            out.writeObject(new SavingsAccount("Farhan", 15000));            System.out.println("Writing worked");        }        try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray()))) {            in.readObject();            System.out.println("Reading worked");        } catch (InvalidClassException e) {            System.out.println("Reading failed: " + e.getMessage());        }    }}
Output
Writing worked
Reading failed: SavingsAccount; no valid constructor

What this code does

  • Account is not serializable and has only Account(String holder), so Java has no constructor it can call for the parent part.
  • Writing works, but reading throws InvalidClassException with the message SavingsAccount; no valid constructor.
  • Fix it by making Account serializable, or by giving it a no-argument constructor if losing holder is acceptable.

If the parent class is not serializable, only the child's fields are saved. On reading, Java calls the parent's no-argument constructor to set up the parent's fields, so they get whatever that constructor gives them, not the saved values. If that non-serializable parent has no no-argument constructor, reading fails with InvalidClassException and the message "no valid constructor". Writing still works, so the bug shows up only when someone tries to load the file.

Next step

Check your understanding

12 quick questions