Prerequisite : – Serialization, Inheritance
Serialization is a mechanism of converting the state of an object into a byte stream. Deserialization is the reverse process where the byte stream is used to recreate the actual Java object in memory. This mechanism is used to persist the object.
There are some cases of Serialization with respect to inheritance :
- Case 1: If superclass is serializable then subclass is automatically serializable : If superclass is Serializable, then by default every subclass is serializable. Hence, even though subclass doesn’t implement Serializable interface( and if it’s superclass implements Serializable), then we can serialize subclass object.
// Java program to demonstrate// that if superclass is// serializable then subclass// is automatically serializableimportjava.io.FileInputStream;importjava.io.FileOutputStream;importjava.io.ObjectInputStream;importjava.io.ObjectOutputStream;importjava.io.Serializable;// superclass A// implementing Serializable interfaceclassAimplementsSerializable{inti;// parameterized constructorpublicA(inti){this.i = i;}}// subclass B// B class doesn't implement Serializable// interface.classBextendsA{intj;// parameterized constructorpublicB(inti,intj){super(i);this.j = j;}}// Driver classpublicclassTest{publicstaticvoidmain(String[] args)throwsException{B b1 =newB(10,20);System.out.println("i = "+ b1.i);System.out.println("j = "+ b1.j);/* Serializing B's(subclass) object *///Saving of object in a fileFileOutputStream fos =newFileOutputStream("abc.ser");ObjectOutputStream oos =newObjectOutputStream(fos);// Method for serialization of B's class objectoos.writeObject(b1);// closing streamsoos.close();fos.close();System.out.println("Object has been serialized");/* De-Serializing B's(subclass) object */// Reading the object from a fileFileInputStream fis =newFileInputStream("abc.ser");ObjectInputStream ois =newObjectInputStream(fis);// Method for de-serialization of B's class objectB b2 = (B)ois.readObject();// closing streamsois.close();fis.close();System.out.println("Object has been deserialized");System.out.println("i = "+ b2.i);System.out.println("j = "+ b2.j);}}chevron_rightfilter_noneOutput:
i = 10 j = 20 Object has been serialized Object has been deserialized i = 10 j = 20
- If a superclass is not serializable then subclass can still be serialized : Even though superclass doesn’t implements Serializable interface, we can serialize subclass object if subclass itself implements Serializable interface. So we can say that to serialize subclass object, superclass need not to be serializable. But what happens with the instances of superclass during serialization in this case. The following procedure explain this.
What happens when a class is serializable but its superclass is not ?
- Serialization: At the time of serialization, if any instance variable is inheriting from non-serializable superclass, then JVM ignores original value of that instance variable and save default value to the file.
- De- Serialization: At the time of de-serialization, if any non-serializable superclass is present, then JVM will execute instance control flow in the superclass. To execute instance control flow in a class, JVM will always invoke default(no-arg) constructor of that class. So every non-serializable superclass must necessarily contain default constructor, otherwise we will get runtime-exception.
// Java program to demonstrate// the case if superclass need// not to be serializable// while serializing subclassimportjava.io.FileInputStream;importjava.io.FileOutputStream;importjava.io.ObjectInputStream;importjava.io.ObjectOutputStream;importjava.io.Serializable;;// superclass A// A class doesn't implement Serializable// interface.classA{inti;// parameterized constructorpublicA(inti){this.i = i;}// default constructor// this constructor must be present// otherwise we will get runtime exceptionpublicA(){i =50;System.out.println("A's class constructor called");}}// subclass B// implementing Serializable interfaceclassBextendsAimplementsSerializable{intj;// parameterized constructorpublicB(inti,intj){super(i);this.j = j;}}// Driver classpublicclassTest{publicstaticvoidmain(String[] args)throwsException{B b1 =newB(10,20);System.out.println("i = "+ b1.i);System.out.println("j = "+ b1.j);// Serializing B's(subclass) object//Saving of object in a fileFileOutputStream fos =newFileOutputStream("abc.ser");ObjectOutputStream oos =newObjectOutputStream(fos);// Method for serialization of B's class objectoos.writeObject(b1);// closing streamsoos.close();fos.close();System.out.println("Object has been serialized");// De-Serializing B's(subclass) object// Reading the object from a fileFileInputStream fis =newFileInputStream("abc.ser");ObjectInputStream ois =newObjectInputStream(fis);// Method for de-serialization of B's class objectB b2 = (B)ois.readObject();// closing streamsois.close();fis.close();System.out.println("Object has been deserialized");System.out.println("i = "+ b2.i);System.out.println("j = "+ b2.j);}}chevron_rightfilter_noneOutput:
i = 10 j = 20 Object has been serialized A's class constructor called Object has been deserialized i = 50 j = 20
- If the superclass is serializable but we don’t want the subclass to be serialized : There is no direct way to prevent subclass from serialization in java. One possible way by which a programmer can achieve this is by implementing the writeObject() and readObject() methods in the subclass and needs to throw NotSerializableException from these methods. These methods are executed during serialization and de-serialization respectively. By overriding these methods, we are just implementing our own custom serialization.
// Java program to demonstrate// how to prevent// subclass from serializationimportjava.io.FileInputStream;importjava.io.FileOutputStream;importjava.io.IOException;importjava.io.NotSerializableException;importjava.io.ObjectInputStream;importjava.io.ObjectOutputStream;importjava.io.Serializable;// superclass A// implementing Serializable interfaceclassAimplementsSerializable{inti;// parameterized constructorpublicA(inti){this.i = i;}}// subclass B// B class doesn't implement Serializable// interface.classBextendsA{intj;// parameterized constructorpublicB(inti,intj){super(i);this.j = j;}// By implementing writeObject method,// we can prevent// subclass from serializationprivatevoidwriteObject(ObjectOutputStream out)throwsIOException{thrownewNotSerializableException();}// By implementing readObject method,// we can prevent// subclass from de-serializationprivatevoidreadObject(ObjectInputStream in)throwsIOException{thrownewNotSerializableException();}}// Driver classpublicclassTest{publicstaticvoidmain(String[] args)throwsException{B b1 =newB(10,20);System.out.println("i = "+ b1.i);System.out.println("j = "+ b1.j);// Serializing B's(subclass) object//Saving of object in a fileFileOutputStream fos =newFileOutputStream("abc.ser");ObjectOutputStream oos =newObjectOutputStream(fos);// Method for serialization of B's class objectoos.writeObject(b1);// closing streamsoos.close();fos.close();System.out.println("Object has been serialized");// De-Serializing B's(subclass) object// Reading the object from a fileFileInputStream fis =newFileInputStream("abc.ser");ObjectInputStream ois =newObjectInputStream(fis);// Method for de-serialization of B's class objectB b2 = (B)ois.readObject();// closing streamsois.close();fis.close();System.out.println("Object has been deserialized");System.out.println("i = "+ b2.i);System.out.println("j = "+ b2.j);}}chevron_rightfilter_noneOutput:
i = 10 j = 20 Exception in thread "main" java.io.NotSerializableException at B.writeObject(Test.java:44)
This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important Java and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.
Recommended Posts:
- Object Graph in Java Serialization
- Serialization and Deserialization in Java with Example
- Customized Serialization and Deserialization In Java
- How to prevent Singleton Pattern from Reflection, Serialization and Cloning?
- Inheritance and constructors in Java
- Comparison of Inheritance in C++ and Java
- Java and Multiple Inheritance
- Inheritance in Java
- Using final with Inheritance in Java
- Interfaces and Inheritance in Java
- Java | Inheritance | Question 1
- Java | Inheritance | Question 2
- Java | Inheritance | Question 3
- Java | Inheritance | Question 4
- Java | Inheritance | Question 5
- Java | Inheritance | Question 9
- Java | Inheritance | Question 7
- Java | Inheritance | Question 8
- Java | Inheritance | Question 9
- Delegation vs Inheritance in Java
Improved By : mmcgarg



