I am a bit confused with the advantage of using Externalizable over Serializable in java. Particularly if I take the following example of a Person class.
The first example use Serializable interface
public class Person implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private int age;
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
private void writeObject(ObjectOutputStream out) throws IOException {
out.writeObject(name);
out.writeInt(age);
}
private void readObject(ObjectInputStream in) throws ClassNotFoundException,
IOException {
name = (String) in.readObject();
age = in.readInt();
}
}
The second example use Externalizable interface
public class Person implements Externalizable{
private static final long serialVersionUID = 1L;
private String name;
private int age;
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void writeExternal(ObjectOutput out) throws IOException {
out.writeObject(name);
out.writeInt(age);
}
public void readExternal(ObjectInput in) throws IOException,
ClassNotFoundException {
name = (String) in.readObject();
age = in.readInt();
}
}
According to the theory, we should use Externalizable where ever possible. But considering above example is there any benefit of using Externalizable interface over Serializable? Or both the methods will be same?
In terms of above-mentioned code, will using Externalizable over Serializable make any difference?