假设你有这两个类,Foo 和 Bar,其中 Bar 扩展 Foo 并实现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;
}
}
请注意, Foo 没有实现Serializable
. 那么当 bar 被序列化时会发生什么?
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);
}
它打印“默认 21”。问题是,为什么在类未序列化时会调用默认构造函数?