Short answer: Yes, if the parent class is serialized, then the child class is automatically serialized.
Long answer:
If the Parent class is Serializable, then the child class is Serializable by default. The JVM checks to see if the parent class implements Serializable, and if so, it also considers that the child class is also serializable. Therefore, Serialization is an inherited concept that comes from parent to child.
public class ParentSerializableNotChild {
public static void main(String[] args) throws Exception{ Child chileSerialize = new Child();
If the parent class is not serializable, then the child class can also be serialized. The best example of this is the Object class, the Object class does not implement Serializable, but any class that is a child of the Object class can implement Serializable.
public class ChildSerializedParentNot {
public static void main(String[] args) throws Exception{ Dogy d = new Dogy(); di = 888; dj = 999; FileOutputStream fos = new FileOutputStream("inheritance.ser"); ObjectOutputStream oos = new ObjectOutputStream(fos); System.out.println("Serializing"); oos.writeObject(d); FileInputStream fis = new FileInputStream("inheritance.ser"); ObjectInputStream ois = new ObjectInputStream(fis); System.out.println("Deserializing"); Dogy d2 = (Dogy) ois.readObject(); System.out.println(d2.i + "-----" + d2.j); } } class Animal{ int i = 10; Animal(){ System.out.println("Parent class cons"); } } class Dogy extends Animal implements Serializable{ Dogy(){ System.out.println("Child class constructor"); } int j = 20; }
Exit:
Parent class cons
Child class constructor
Serialization
deserialization
Parent class cons
10,999 -----
Above, there are 3 cases where a child is serialized, but is not a parent.
Case 1: during serialization, the JVM checks to see if any instance variable comes from a non-serialized parent class. If so, then the parent class is not serializable and its instance variable participates in serialization, then jvm ignores the value of the instance variable and saves the default value in the file. (In the example above, I am stored as 0 in a file).
Case 2: during deserialization, the JVM checks to see if any instance variable comes from a non-serialized parent class. If so, the JVM will run INSTANCE CONTROL FLOW, and the original value of the object will be restored.
INSTANCE CONTROL FLOW (in short) http://java2bigdata.blogspot.in/2015/05/instance-control-flow-in-java.html
1. Identification of a member of the authority.
2. Performing the assignment and instantiation of the instance variable.
3. Execution of the designer.
Case 3: Because the constructor runs in the instance control flow. Therefore, in the case of a non-serialized parent, a constructor without arguments is called, this constructor can be provided by the user or created by jvm. If there is no constructor without arguments, this will throw an InvalidClassException.
Utsav
source share