Serialization and Inheritance
The inheritance hierarchy of an object also determines what its state will be after it is deserialized. An object will have the same state at deserialization as it had at the time it was serialized if all its superclasses are also serializable. This is because the normal object creation and initialization procedure using constructors is not run during deserialization.
However, if any superclass of an object is not serializable, then the normal creation procedure using no-argument or default constructors is run, starting at the first non-serializable superclass, all the way up to the Object class. This means that the state at deserialization might not be the same as at the time the object was serialized because superconstructors run during deserialization may have initialized the state of the object. If the non-serializable superclass does not provide a non-argument constructor or the default constructor, a java.io.InvalidClassException is thrown during deserialization.
Example 20.9 illustrates how inheritance affects serialization. The Student class is a subclass of the Person class. Whether the superclass Person is serializable or not has implications for serializing objects of the Student subclass, in particular, when their byte representation is deserialized.
Superclass Is Serializable
If the superclass is serializable, then any object of a subclass is also serializable. In Example 20.9, the code at (4) in the class SerialInheritance serializes a Student object:
Student student = new Student(“Pendu”, 1007);
System.out.println(“Before writing: ” + student);
outputStream.writeObject(student);
The corresponding code for deserialization of the streamed object is at (5) in the class SerialInheritance:
Student student = (Student) inputStream.readObject();
System.out.println(“After reading: ” + student);
We get the following output from the program in Example 20.9 when it is run with (1a) and (3a) in the Person class and the Student class, respectively—that is, when the superclass is serializable and so is the subclass, by virtue of inheritance.
The results show that the object state prior to serialization is identical to the object state after deserialization. In this case, no superclass constructors were run during deserialization.
Before writing: Student state(Pendu, 1007)
After reading: Student state(Pendu, 1007)