Object Serialization with Inheritance in Java Programming

Java 8Object Oriented ProgrammingProgramming

Serialization is the process of changing the state of an object into the byte stream so that the byte stream can return back into a copy of the object

In Java, an object is said to be serializable if its class or parent classes implement either the Serializable interface or the Externalizable interface.

Deserialization is converting the serialized object back into a copy of the object.

There are three cases of Object Serialization with inheritance.

  • The child class is automatically serializable if the parent class is serializable

  • A child class can still be serialized even if the parent class is not serializable

  • If we want the child class not be serialized even if the parent class is serializable

Let us see an example where the child class automatically becomes serializable when the parent class is serializable −

 Live Demo

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.NotSerializableException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
class Parent implements Serializable {
   int i = 33;
}
class Child extends Parent {
   int j = 21;
}
public class Example {
   public static void main(String[] args) throws IOException, ClassNotFoundException {
      Child writer = new Child();
      FileOutputStream fos = new FileOutputStream("file.txt");
      ObjectOutputStream oos = new ObjectOutputStream(fos);
      oos.writeObject(writer);
      FileInputStream fis = new FileInputStream("file.txt");
      ObjectInputStream ois = new ObjectInputStream(fis);
      Child reader = (Child)ois.readObject();
      System.out.println(reader.i+","+reader.j);
   }
}

output

33,21
raja
Published on 03-Jan-2019 10:08:35
Advertisements