Externalizable Interface in Java

Java Programming Java8Object Oriented Programming

Externalization is used whenever we need to customize serialization mechanism. If a class implements an Externalizable interface then, object serialization will be done using writeExternal() method. Whereas at receiver's end when an Externalizable object is a reconstructed instance will be created using no argument constructor and then the readExternal() method is called.

If a class implements only Serializable interface object serialization will be done using ObjectoutputStream. At the receiver's end, the serializable object is reconstructed using ObjectInputStream.

Below example showcases usage of Externalizable interface.


import java.io.Externalizable;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;

public class Tester {
   public static void main(String[] args) {

      Employee e = new Employee();
      e.name = "Reyan Ali";
      e.age = 30;
      try (
         FileOutputStream fileOut = new FileOutputStream("test.txt");
         ObjectOutputStream out = new ObjectOutputStream(fileOut);
      ) {
      }catch (IOException i) {
      try (
         FileInputStream fileIn = new FileInputStream("test.txt");
         ObjectInputStream in = new ObjectInputStream(fileIn);
      ) {
         e = (Employee)in.readObject();
      } catch (IOException i) {
      } catch (ClassNotFoundException e1) {

class Employee implements Externalizable {
   public Employee(){}
   String name;
   int age;
   public void writeExternal(ObjectOutput out) throws IOException {
   public void readExternal(ObjectInput in) throws IOException,
   ClassNotFoundException {
      name = (String)in.readObject();
      age = in.readInt();

This will produce the following result −


Reyan Ali
Updated on 21-Jun-2020 13:49:30