I'm learning about Serialization and Inheritance and I don't understand who call the no-arg constructor at the deserialization process. The superclass A doesn't implement Serializable and subclass B extends A implements Serializable.
superclass A
public class A { int i; public A(int i) { this.i = i; } public A() { i = 50; System.out.println("A's class constructor called"); } } subclass B
import java.io.Serializable; public class B extends A implements Serializable { int j; // parameterized constructor public B(int i,int j) { super(i); this.j = j; } } Driver Class
import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; public class Test { public static void main(String[] args) throws Exception { B b1 = new B(10,20); System.out.println("i = " + b1.i); System.out.println("j = " + b1.j); // Serializing B's(subclass) object //Saving of object in a file FileOutputStream fos = new FileOutputStream("abc.ser"); ObjectOutputStream oos = new ObjectOutputStream(fos); // Method for serialization of B's class object oos.writeObject(b1); // closing streams oos.close(); fos.close(); System.out.println("Object has been serialized"); // De-Serializing B's(subclass) object // Reading the object from a file FileInputStream fis = new FileInputStream("abc.ser"); ObjectInputStream ois = new ObjectInputStream(fis); // Method for de-serialization of B's class object B b2 = (B)ois.readObject(); // The A() constructor is called here // closing streams ois.close(); fis.close(); System.out.println("Object has been deserialized"); System.out.println("i = " + b2.i); System.out.println("j = " + b2.j); } } If I delete the A() constructor I get the InvalidClassException. I see that A() is called when the b2 object is created but I don't understand why this A() is called at this statement and who called it.
When the b1 object is created the B(int i, int j) constructor and also A(int i) constructor are called. This is easy to understand. But I don't understand why A() constructor is called when b2 object is created.