Java Design Pattern
Introduction to Java 10
Introduction to Java 11
Introduction to Java 12

Object graphs in serialization

Whenever we are serializing an object ,the set of all objects which are reachable form that object will be serialized automatically. This group of objects is nothing but Object Graph.
In object graph every object should be serializable if atleast one object is not serializable then we will get runtime execution saying NonSerializableExecution.

Example:
import java.io.*;
class Dog implements Serializable
{
	Cat c=new Cat();
}
class Cat implements Serializable
{
	Rat r=new Rat();
}
class Rat implements Serializable
{
	int j=20;
}
class SerializeDemo2
{
	public static void main(String args[])throws Exception
	{
		Dog d1=new Dog();
		FileOutputStream fos=new FileOutputStream("abc.ser");
		ObjectOutputStream oos=new ObjectOutputStream(fos);
		oos.writeObject(d1);
		FileInputStream fis=new FileInputStream("abc.ser");
		ObjectInputStream ois=new ObjectInputStream(fis);
		Dog d2=(Dog) ois.readObject();
		System.out.println(d2.c.r.j);
	}
}
Output

20

In the above program whenever we are serializing Dog object automatically Cat and Rat objects got serialized because these are part of ObjectGraph of Dog.
Among Dog, Cat and Rat objects if at least one object is not serializable then we will get Runtime Exception saying NotSerializableExecution.

About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.


We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc






 PreviousNext