0

NotSerializableException will be thrown out when serializing a Object of Class A if there is a field which not impleting Serializable interface and this is expected. However if we write a subclass AC of A, and serialize the object of AC, serialization will be successful. Why?

Case 1 throws out a NotSerializableException because TestField is not serializable :

public class SerTest {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        ObjectOutputStream oos1 = new ObjectOutputStream(new FileOutputStream("person.txt"));
        oos1.writeObject(new Ser());
    }
}

class Ser implements Serializable  {
    public TestField testField = new TestField(2);
}

case 2, still successes even though TestField is still not seriable.

public class SerTest {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("person.txt"));
        oos.writeObject(new SerChild());
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("person.txt"));
        SerChild c = (SerChild)(ois.readObject());
        System.out.println(c.testField);
    }
}

class Ser {
    public TestField testField = new TestField(2);
}

class SerChild extends Ser implements Serializable {
}

class TestField {
    public int age;
    public TestField(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "TestField{" +
                "age=" + age +
                '}';
    }
}
Jack Ma
  • 153
  • 1
  • 11

0 Answers0