當一個父類實現Serializable接口後,他的子類都將自動的實現序列化。
以下驗證了這一點:
package Serial;
import Java.io.Serializable;
public class SuperC implements Serializable {//父類實現了序列化
int supervalue;
public SuperC(int supervalue) {
this.supervalue = supervalue;
}
public String toString() {
return "supervalue: "+supervalue;
}
}
public class SubC extends SuperC {//子類
int subvalue;
public SubC(int supervalue,int subvalue) {
super(supervalue);
this.subvalue=subvalue;
}
public String toString() {
return super.toString()+" sub: "+subvalue;
}
}
public class Test1 {
public static void main(String [] args){
SubC subc=new SubC(100,200);
FileInputStream in=null;
FileOutputStream out=null;
ObjectInputStream oin=null;
ObjectOutputStream oout=null;
try {
out = new FileOutputStream("Test1.txt");//子類序列化
oout = new ObjectOutputStream(out);
oout.writeObject(subc);
oout.close();
oout=null;
in = new FileInputStream("Test1.txt");
oin = new ObjectInputStream(in);
SubC subc2=(SubC)oin.readObject();//子類反序列化
System.out.println(subc2);
} catch (Exception ex){
ex.printStackTrace();
} finally{
…此處省略
}
}
}
運行結果如下:
supervalue: 100 sub: 200
可見子類成功的序列化/反序列化了。
怎管讓子類實現序列化看起來是一件很簡單的事情,但有的時候,往往我們不能夠讓父類實現Serializable接口,原因是有時候父類是抽象的(這並沒有關系),並且父類不能夠強制每個子類都擁有序列化的能力。換句話說父類設計的目的僅僅是為了被繼承。
要為一個沒有實現Serializable接口的父類,編寫一個能夠序列化的子類是一件很麻煩的事情。Java docs中提到:
“To allow subtypes of non-serializable classes to be serialized, the subtype may assume responsibility for saving and restoring the state of the supertype's public, protected, and (if accessible) package fIElds. The subtype may assume this responsibility only if the class it extends has an Accessible no-arg constructor to initialize the class's state. It is an error to declare a class Serializable if this is not the case. The error will be detected at runtime. ”