How serialization works when only subclass implements serializable

If your MyClass holds reference to an object of non serializable class you will get NotSerializable exception at run time. To test, modify MyClass so that it holds a reference to an object of NewClass1. If you run again it will throw an exception.

Deserialization is essentially creating an instance of a serializable class and restoring its properties. During this process the constructor of the serializable class is not called. Rather the no arg constructor of first non serializable super class is called.

In your case the no arg constructor of NewClass1 assigns 10 to its instance variable i. So, during deserialization it's printing 10 instead of 20.


according to the Serializable javadoc

During deserialization, the fields of non-serializable classes will be initialized using the public or protected no-arg constructor of the class. A no-arg constructor must be accessible to the subclass that is serializable. The fields of serializable subclasses will be restored from the stream.

also, serialization exception is only thrown if the class being serialized is not serializable. having non-serializable parents is fine (as long as they have a no-arg constructor). Object itself isnt Serializable, and everything extends it. the quote above also explains why you get different values for the value field - the no-arg constructor for the parent class is set, which sets the value field to 10 - the field belongs to the (non-serializable) parent so its value isnt written to/read from the stream.