Java readObject/writeObject can save/load the parent class (super class), so why do you need read/writeExternal?

Java readObject/writeObject can save/load the parent class (super class), so why do you need read/writeExternal? … here is a solution to the problem.

Java readObject/writeObject can save/load the parent class (super class), so why do you need read/writeExternal?

Core Java Volume II chapter II says that, unlike readObject/writeObject, readExternal/writeExternal can save and recover data, including the super class. I just did an experiment and it seems that readObject/writeObject can do the same thing:

class base implements Serializable{
    protected String field = "xyz";
}
class c1 extends base implements Serializable {
    private String name = "name";
    private int age = 12;

private void readObject(ObjectInputStream ois) {
        System.out.println("readObject!!");
        try {
            field = (String) ois.readObject();
            name = (String) ois.readObject();
            age = ois.readInt();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

private void writeObject(ObjectOutputStream oos) {
        System.out.println("writeObject!!");
        try {
            oos.writeObject(field);
            oos.writeObject(name);
            oos.writeInt(age);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

My question is: when do we need to use readExternal/writeExternal()? I don’t see any work that readExternal/writeExternal can do that readObject/writeObject cannot.

Please help clarify. Thank you so much.

Solution

Both Serializable and Extenalizable are used to serialize or persist Java objects, but they differ in different ways.
In the case of Serializable, the Java Virtual Machine has full control over serialized objects, while in the case of Externalizable, applications have control over persisted objects. The writeExternal() and readExternal() methods provide applications with complete control over the format and content of the serialization process, which can be used to improve the performance and speed of the serialization process.

Related Problems and Solutions