Non-static nested classes that implement Serializable must be defined in an enclosing class that is also serializable. Non-static nested classes retain an implicit reference to an instance of their enclosing class. If the enclosing class is not serializable, the Java serialization mechanism fails with a java.io.NotSerializableException.

To avoid causing a NotSerializableException, do one of the following:

In the following example, the class WrongSession cannot be serialized without causing a NotSerializableException, because it is enclosed by a non-serializable class. However, the class Session can be serialized because it is declared as static.

  • Java Object Serialization Specification: 1.10 The Serializable Interface, 2.1 The ObjectOutputStream Class.