| 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: Serializable cannot be resolved or is not a valid superinterface at Serial.SubC.(SubC.java:15) at Serial.Test1.main(Test1.java:19) Exception in thread "main" |
| public abstract class SuperC { int supervalue; public SuperC(int supervalue) { this.supervalue = supervalue; } public SuperC(){}//增加一个无参的constructor public String toString() { return "supervalue: "+supervalue; } } public class SubC extends SuperC implements Serializable { int subvalue; public SubC(int supervalue,int subvalue) { super(supervalue); this.subvalue=subvalue; } public String toString() { return super.toString()+" sub: "+subvalue; } private void writeObject(java.io.ObjectOutputStream out) throws IOException{ out.defaultWriteObject();//先序列化对象 out.writeInt(supervalue);//再序列化父类的域 } private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException{ in.defaultReadObject();//先反序列化对象 supervalue=in.readInt();//再反序列化父类的域 } } |