Effects of Inheritance on Serialization

If a superclass is Serializable, then according to normal Java interface rules, all subclasses of that class automatically implement Serializable implicitly.

What happens if a superclass is not marked Serializable, but the subclass is marked Serializable? Can the subclass still be serialized? Will the superclass also be serialized?

In this scenario, when an object is deserialized, then any instance variables you INHERIT from that superclass will be reset to the values they were given during the original construction of the object. In other words, the constructor of the superclass WILL run!

In fact, every constructor of the superclass in the inheritance tree till the first non-serialzable class constructor will run.

If you do not have a constructor with no arguments in any of such classes, then the JVM will throw InvalidClassException!!!

No comments:

Post a Comment

Followers