How are the constructors called during serialization and deserialization
First of all at the time of Deserialization no any construtor called, all field's value will be set by reflection.
If you mark your class as Serializable than JVM set the field's value by reflection at the time of Deserialization and after that JVM looks for it's super class and if that is not marked as Serializable then default constructor will call and then call next super class and so on.
take a look for this scenario :
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class Test {
public static void main(String...strings) throws IOException, ClassNotFoundException {
Employee emp = new Employee();
emp.companyName = "XYZ";
emp.employeeName = "ABC";
getSirielization(emp);
Employee em = (Employee) getDeSirielization();
System.out.println(em.companyName+" "+em.employeeName);
}
public static void getSirielization(Object object) throws IOException {
File f = new File("/home/server/ironman/serializedFile.txt");
FileOutputStream fo = new FileOutputStream(f);
ObjectOutputStream oob = new ObjectOutputStream(fo);
oob.writeObject(object);
}
public static Object getDeSirielization() throws IOException, ClassNotFoundException {
File f = new File("/home/server/ironman/serializedFile.txt");
FileInputStream fo = new FileInputStream(f);
ObjectInputStream oob = new ObjectInputStream(fo);
Object object = oob.readObject();
return object;
}
}
class Company {
String companyName;
public Company() {
System.out.println("Company-Default");
}
}
class Employee extends Company implements Serializable {
private static final long serialVersionUID = -3830853389460498676L;
String employeeName;
public Employee() {
System.out.println("hello2");
}
}