Sunday, December 2, 2012

The relationship between Serialization and Inheritance

There is no method defined in Serializable interface. It is just a marker interface that marked on a class that it support serialization. It is also important to know that ObjectOutputStream can write both objects and primitive types, as it implement ObjectInput and DataInput interfaces. The serielization mechanism will follow object references and write whole hierarchies of objects. However, if any superclass of an object is not serializable, then the normal object creation using constructor is call, start from the very first non-serializable superclass, all the way up to the Object class.

A code is worth a thousand nonsense:
public class Person {

   private String name;
 
   Person() {
      System.out.println("Person constructor is called.");
   }

   ...
}

public class Student extends Person implements Serializable {

  private static final long serialVersionUID = 8306482247141552618L;

  public Student(String name, long ID) {
    super(name);
    this.ID = ID;
  }
  ...
}

The code shows that Person class is not implement Serializable whereas Student class did. By the time during the deserialization happened to Student object, the default constructor of Person class is called. Thus "Person constructor is called" will output in the console.
FileInputStream inputFile = new FileInputStream("saveObject");
ObjectInputStream inputStream = new ObjectInputStream(inputFile);
  
Student student = (Student) inputStream.readObject();

No comments: