情境:一個子類實現了 Serializable 接口,java
解決:函數
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();//再反序列化父類的域 } }
Transient 關鍵字的做用是控制變量的序列化,this