How does de-serialization makes constructor calls ?
Hi,
Please refer to the code below and the output generated:
Code:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class SerlDeSerl {
public static void main(String[] args) throws Exception {
System.out.print("Writing");
Sub sub = new Sub();
ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream("D:\\Test\\Test.serl"));
os.writeObject(sub);
System.out.print("Reading");
ObjectInputStream is = new ObjectInputStream(new FileInputStream("D:\\Test\\Test.serl"));
is.readObject();
}
}
class Super {
Super() {
System.out.print("Super");
}
}
class Sub extends Super implements Serializable {
Sub() {
System.out.print("Sub");
}
}
The output is WritingSuperSubReadingSuper.
During the de-serialization process only the constructor of Super is called and not the Sub even we are de-serializing the Sub object. Why is it so ?
The behaviour (output) of the code changes further if we remove 'implements Serializable' from the Sub class definition and put it in Super class definition. In this case, the output is: WritingSuperSubReading.
How does constructor calls happens during the de-serialization process ?