Object Graph in Java Serialization


An object graph contains a set of objects that are automatically serialized given that the object that contains the reference is serialized too. Any object that is serialized and contains an object reference, the object reference will be serialized by the JVM.

Example

 Live Demo

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
class One implements Serializable{
   Two s2 = new Two();
}
class Two implements Serializable{
   Three s3 = new Three();
}
class Three implements Serializable{
   int i = 34;
   int j = 67;
}
public class Demo_Serialize{
   public static void main(String args[]) throws Exception{
      One s1 = new One();
      FileOutputStream my_fos = new FileOutputStream("abc.ser");
      ObjectOutputStream my_oos = new ObjectOutputStream(my_fos);
      my_oos.writeObject(s1);
      my_fos.close();
      my_oos.close();
      FileInputStream my_fis = new FileInputStream("abc.ser");
      ObjectInputStream my_ois = new ObjectInputStream(my_fis);
      One my_obj = (One) my_ois.readObject();
      my_fis.close();
      my_ois.close();
      System.out.println("Value of i after it is serialized is " + my_obj.s2.s3.i);
      System.out.println("Value of j after it is serialized is "+my_obj.s2.s3.j);
   }
}

Output

Value of i after it is serialized is 34
Value of j after it is serialized is 67

A class named ‘One’ inherits from the class ‘Serializable’. Here, another instance of a different class is created. The same class is inherited by the ‘Serializable’ class. Again, a different instance is created within this class.

Another class inherits the ‘Serializable’ class. Here, two integers are defined, and another class named ‘Demo_Serialize’ is created. Here, the main function is defined. An instance of the first class is defined, and an instance of FileOutputStream and ObjectOutputStream are created. The objects are written using these streams. Later, the streams are closed. This is done once more to serialize the data. The relevant output is displayed on the console.

Updated on: 17-Aug-2020

541 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements