谈谈J2SE中的序列化(二)
作者:Favo yang
favoyang@yahoo.com
当序列化碰到继续…
当一个父类实现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{
…此处省略
}
}
}