Will serialization save superclass fields?

My subclass implements Serializable, but my superclass does not work.

Both subclasses and superclasses contain variables that must be saved as part of the state of the subclass.

Will serialization save superclass fields?

+7
source share
2 answers

Superclass fields cannot be serialized unless they are Serializable. Here is a summary of some Java serialization rules:

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

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

  • The no-arg constructor of each non-serializable superclass will work when the object is deserialized. However, deserialized objects? the constructor does not start during deserialization.

  • The class must be visible at the serialization point.

  • All primitive types are serializable.

  • Temporary fields (with a transition modifier) โ€‹โ€‹are NOT serialized (that is, they are not saved or restored). A class that implements fields Serializablemust -transient classes that do not support serialization (for example, file stream).

  • Static fields (with static modifier) โ€‹โ€‹are not serialized.

  • If member variables of a serializable object reference a non-serializable object, the code will be compiled, but a RumtimeException will be thrown.

+20
source

If the superclass is not Serializable , the fields will not be serialized. Moreover, you need to have a no-args constructor in the superclass.

As the documentation says:

During deserialization, fields of non-serialization classes will be initialized using the public or protected constructor of the no-arg class. The no-arg constructor must be available for the subclass that is being serialized.

+3
source

All Articles