<<Previous
- If the parent is Serializable then every child is by default Serializable that is Serializable nature will be inherited from parent to child.
package com.javamonkeys.serialization; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; class Animal implements Serializable{ int i=10; } class Tiger extends Animal{ int j=20; } public class SerializeInheritExample { public static void main(String[] args)throws IOException, ClassNotFoundException { Tiger t = new Tiger(); FileOutputStream fiOutputStream = new FileOutputStream("D:\\serializablefile.ser"); ObjectOutputStream oStream = new ObjectOutputStream(fiOutputStream); oStream.writeObject(t); FileInputStream fileInputStream = new FileInputStream("D:\\serializablefile.ser"); ObjectInputStream oInputStream = new ObjectInputStream(fileInputStream); Tiger tig = (Tiger)oInputStream.readObject(); System.out.println(tig.i+"......."+tig.j); } }Output: 10…….20
- Even though parent is not Serializable and its child class is Serializable, At the time of serialization if any variable inheriting from non Serializable parent then JVM ignores original value and default value will be sent to the file.
- At the time of de-serialization JVM checks is there any parent class is non Serializable or not. If any parent is non Serializable then JVM creates an object of that class and shares its instance variables to the current object.
- For creating object of non Serializable parent JVM always invokes no-argument constructor. Hence every non Serializable parent should compulsory contain no-argument constructor otherwise we will get runtime exception InstantiationException.
package com.javamonkeys.serialization; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; class Animal { int i=10; Animal(){ System.out.println("Animal class constructor"); } } class Tiger extends Animal implements Serializable{ int j=20; Tiger(){ System.out.println("Tiger class constructor"); } } public class SerializeInheritExample { public static void main(String[] args)throws IOException, ClassNotFoundException { Tiger t = new Tiger(); t.i=100; t.j=1000; FileOutputStream fiOutputStream = new FileOutputStream("D:\\serializablefile.ser"); ObjectOutputStream oStream = new ObjectOutputStream(fiOutputStream); oStream.writeObject(t); System.out.println("Deserialization process started"); FileInputStream fileInputStream = new FileInputStream("D:\\serializablefile.ser"); ObjectInputStream oInputStream = new ObjectInputStream(fileInputStream); Tiger tig = (Tiger)oInputStream.readObject(); System.out.println(tig.i+"......."+tig.j); } }Output:
Animal class constructor
Tiger class constructor
Deserialization process started
Animal class constructor
10.......1000