Serialization in java — Inheritance

  1. Case 1: If superclass is serializable then subclass is automatically serializable : If superclass is Serializable, then by default every subclass is serializable. Hence, even though subclass doesn’t implement Serializable interface( and if it’s superclass implements Serializable), then we can serialize subclass object.
i = 10
j = 20
Object has been serialized
Object has been deserialized
i = 10
j = 20
  • Serialization: At the time of serialization, if any instance variable is inheriting from non-serializable superclass, then JVM ignores original value of that instance variable and save default value to the file.
  • De- Serialization: At the time of de-serialization, if any non-serializable superclass is present, then JVM will execute instance control flow in the superclass. To execute instance control flow in a class, JVM will always invoke default(no-arg) constructor of that class. So every non-serializable superclass must necessarily contain default constructor, otherwise we will get runtime-exception.
i = 10
j = 20
Object has been serialized
A's class constructor called
Object has been deserialized
i = 50
j = 20

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Sunaina Goyal

Sunaina Goyal

Developer, melomaniac, philospher, tea lover