サブクラスのみSerializable
がインターフェースを実装しています。
import java.io.*;
public class NewClass1{
private int i;
NewClass1(){
i=10;
}
int getVal() {
return i;
}
void setVal(int i) {
this.i=i;
}
}
class MyClass extends NewClass1 implements Serializable{
private String s;
private NewClass1 n;
MyClass(String s) {
this.s = s;
setVal(20);
}
public String toString() {
return s + " " + getVal();
}
public static void main(String args[]) {
MyClass m = new MyClass("Serial");
try {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("serial.txt"));
oos.writeObject(m); //writing current state
oos.flush();
oos.close();
System.out.print(m); // display current state object value
} catch (IOException e) {
System.out.print(e);
}
try {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("serial.txt"));
MyClass o = (MyClass) ois.readObject(); // reading saved object
ois.close();
System.out.print(o); // display saved object state
} catch (Exception e) {
System.out.print(e);
}
}
}
ここで気づいたことの 1 つは、親クラスがシリアル化されていないことです。NotSerializableException
次に、実際にスローしなかったのはなぜですか
出力
Serial 20
Serial 10
Serialization
また、出力は ととは異なりますDe-serialization
。親クラスが実装されていないためSerializable
です。しかし、誰かが私に説明すると、オブジェクトのシリアル化と逆シリアル化中に何が起こるか. どのように値を変更しますか? 私は理解できません。また、プログラムでコメントを使用しました。ですから、どこかで間違っていたら教えてください。