Why is constructor of the Food and Fruit class called when I deserialize where as the constructor of SkinFruit and Banana2 is not called in the below example?
Suppose I have following class hierarchy
class Food{
public Food() { System.out.println("1"); }
}
class Fruit extends Food {
public Fruit() { System.out.print("2"); }
}
class SkinFruit extends Fruit implements Serializable{
SkinFruit() { System.out.print("3"); }
}
public class Banana2 extends SkinFruit {
private static final long serialVersionUID = 1L;
int size = 42;
public static void main(String [] args) {
Banana2 b = new Banana2();
FileOutputStream fost;
try {
fost = new FileOutputStream(new File("d:/testbanana.ser"));
ObjectOutputStream oostr= new ObjectOutputStream(fost);
oostr.writeObject(b);
oostr.flush();
oostr.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
try {
FileInputStream fin= new FileInputStream(new File("d:/testbanana.ser"));
ObjectInputStream objin= new ObjectInputStream(fin);
b=(Banana2)objin.readObject();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
System.out.println(" restored "+ b.size + "" );
}
}
Neither is called, because your class is not Serializable.
You cannot call the
B()without callingA()because B calls A.Consider the following program
prints
A is the non Serializable parent of B. It is not Serialized and so the constructor has to be called to set any fields which need to be set. However, B, C and D are all Serializable and their fields have been serializable and will be reset. There is no need to call the constructor.