Say you have these two classes, Foo and Bar where Bar extends Foo and implements Serializable
class Foo {
public String name;
public Foo() {
this.name = "Default";
}
public Foo(String name) {
this.name = name;
}
}
class Bar extends Foo implements java.io.Serializable {
public int id;
public Bar(String name, int id) {
super(name);
this.id = id;
}
}
Notice that Foo doesn't implement Serializable
. So what happens when bar is serialized?
public static void main(String[] args) throws Exception {
FileOutputStream fStream=new FileOutputStream("objects.dat");
ObjectOutputStream oStream=new ObjectOutputStream(fStream);
Bar bar=new Bar("myName",21);
oStream.writeObject(bar);
FileInputStream ifstream = new FileInputStream("objects.dat");
ObjectInputStream istream = new ObjectInputStream(ifstream);
Bar bar1 = (Bar) istream.readObject();
System.out.println(bar1.name + " " + bar1.id);
}
it prints "Default 21". The question is, why the default constructor get called when the class is not serialized?
Actually when you will read the parent class object back as it's not serialize at all.. so for the non serialize things again JVM go through the same process as it use to go when we create the new object using new keyword.
Serializable is just a "marker interface" for a given class.
But that class must adhere to certain rules:
to answer @Sleiman Jneidi question asked in comment, in oracle documentation mentioned above, its clearly mentioned
Thus, default no-arg constructor of class Foo called of, resulted in initialization.
it may be that the defaultWriteObject can only write the non-static and non-transient fields of the current class. Once the superclass does not implements the Serializable interface, the fields in the superclass can not be serialized into the stream.