![]() |
VOOZH | about |
Object Serialization in Java allows you to save (serialize) and restore (deserialize) the state of an object, even when it’s part of an inheritance hierarchy. When dealing with inheritance, the serialization behavior depends on whether the superclass and subclass implement the Serializable interface.
Serialization behavior changes depending on whether the superclass or subclass implements the Serializable interface. There are three main cases to understand:
If the superclass implements Serializable, then its subclasses are automatically serializable, even if they don’t explicitly implement the interface.
Output:
Explanation: Since class A implements Serializable, the subclass B is also serializable automatically. Both i and j retain their values after deserialization.
Even if the superclass doesn’t implement Serializable, a subclass can still be serialized if it implements the Serializable interface. However, instance variables from the non-serializable superclass are not saved during serialization
Note: The non-serializable superclass must have a no-argument constructor, because it will be called during deserialization to reinitialize its part of the object.
i = 10 j = 20 Object has been serialized A's class constructor called Object has been deserialized i = 50 j = 20
Explanation: A is not serializable, so its field i is not saved. During deserialization, A’s default constructor is invoked, setting i = 50. The field j (from B) is restored correctly.
If the superclass implements Serializable, there’s no direct way to stop a subclass from being serialized. However, we can manually block serialization by overriding the following methods in the subclass:
Throw a NotSerializableException inside these methods to prevent serialization and deserialization.
Output:
Explanation: Here, the subclass B overrides writeObject() and readObject() to block serialization. This approach effectively prevents subclass objects from being serialized or deserialized, even though their superclass is serializable.