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
“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. ”
java.lang.Error: Unresolved compilation problem:
新闻热点
疑难解答