0

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?

Delphi
  • 71
  • 1
  • 8
  • Using `Serializable`, you make you class serializable just adding marker interface in signature without need of any extra code (unless you explicitly implement `readObject()`, `writeObject()` methods in special case). In `Externalizable`, implementation is a developer's responsibility. – Alex Salauyou Jul 08 '17 at 19:35
  • In terms of above-mentioned code, will using Externalizable over Serializable make any difference? – Delphi Jul 08 '17 at 19:39
  • you could use `Serializable` and change `readExternal()`, `writeExternal()` to `readObject()`, `writeObject()` if you need special implementation. No difference – Alex Salauyou Jul 08 '17 at 19:40
  • In the above example, will the binary data produced be same for serialization and externalization process? – Delphi Jan 02 '20 at 13:31

0 Answers0