Object Construction in Serialization
My previous article on exploring java serialization is a box office hit. In continuation to that and popular request, I am going to write on how instances are created during serialize and de-serialize process.
There is a mystery. If you strongly believe that the constructor of a class is called everytime when an object is instantiated, then you have got a surprise.
- RULE1: When you serialize an object, the whole inheritance hierarchy is serialized till the first non-serializable class of that object.
To understand the above, consider the two example scenarios given through diagram,
Serialization Inheritance Hierarchy Example 1
Serialization Inheritance Hierarchy Example 2
- Vehicle is the first non-serializable class.
- Animal is the first non-serializable class.
Therefore, when you serialize an object of HybridCycle or Lion, as a chain it will save the state till Vehicle and Animal classes respectively.
Animal class must have an empty constructor. In the case of Cycle inheritance chain, Vehicle is the last class. Vehicle implicitly extends Object and thus gets access to an empty constructor.
- RULE2: The first non-serializable class must have an empty constructor.
This rule makes sense when you de-serialize. When you de-serialize, the object is not constructed using it’s constructors. Objects are instantiated using the saved state when it was serialized. Deserialization stops at the first non-serializable class and the empy constructor will be used.
- For Vehicle scenario, Object’s empty constructor will be used.
- Animal must have an empty constructor. If you have a parameterized constructor in Animal, you must explicitly add the empty constructor or you will get compilation error.
This Core Java tutorial was added on 11/12/2011.