“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"
果真如docs中所说的一样,父类缺少无参构造函数是不行的。
接下来,按照docs中的建议我们改写这个例子:
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; }