15

My subclass implements Serializable, but my superclass does not.

Both subclass and superclass contain variables that need to be saved as part of the state of the subclass.

Will serialization save the superclass fields?

Danijel
  • 8,198
  • 18
  • 69
  • 133

2 Answers2

29

A superclass fields cannot be serialized if it is not Serializable.Here is a summary of some rules of Java serialization:

  • An object is serializable only if its class or its superclass implements the Serializable (or Externalizable) interface.

  • An object is serializable (itself implements the Serializable interface) even if its superclass is not. However, the firstsuperclass in the hierarchy of the serializable class, that does not implements Serializable interface, MUST have a no-arg constructor. If this is violated, readObject() will produce a java.io.InvalidClassException in runtime.

  • The no-arg contructor of every non-serializable superclass will run when an object is deserialized. However, the deserialized objects? constructor does not run when it is deserialized.

  • The class must be visible at the point of serialization.

  • All primitive types are serializable.

  • Transient fields (with transient modifier) are NOT serialized, (i.e., not saved or restored). A class that implements Serializablemust mark -transient fields of classes that do not support serialization (e.g., a file stream).

  • Static fields (with static modifier) are Not serialized.

  • If member variables of a serializable object reference to a non-serializable object, the code will compile but a RumtimeExceptionwill be thrown.

Martin
  • 2,347
  • 1
  • 21
  • 21
Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136
  • 6
    Please provide a source if you copy-paste solution (for any interested people: http://www.xyzws.com/Javafaq/what-are-rules-of-serialization-in-java/208) – Michal Borek May 08 '13 at 14:18
5

If superclass is not Serializable fields won't be serialized. What is more you need to have no-args constructor in superclass.

As documentation says:

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.

Michal Borek
  • 4,584
  • 2
  • 30
  • 40