core java volumeII chapter II says, unlike readObject/writeObject, readExternal/writeExternal are able to save and restore data including the super class. I just did an experiment, and seems readObject/writeObject could do the same work:
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 should we need to use readExternal/writeExternal()? I don't see any work that readExternal/writeExternal could do while readObject/writeObject could not.
Please kindly help to clarify. Thanks a lot.
Both Serializable and Extenalizable are used to serialize or persist java objects but the way they do is differs. In case of Serializable Java Virtual machine has full control for serializing object while in case of Externalizable, application gets control for persisting objects. writeExternal() and readExternal() method provides complete control on format and content of Serialization process to application which can be leveraged to increase performance and speed of serialization process.