Serialization among subclass

java, serialization

Solution

Is not possible to serialize B without modifying A to have an accesible no argument constructor.

From javadoc of java.io.Serializable

To allow subtypes of non-serializable classes to be serialized, the subtype may assume responsibility for saving and restoring the state of the supertype's public, protected, and (if accessible) package fields. The subtype may assume this responsibility only if the class it extends has an accessible no-arg constructor to initialize the class's state. It is an error to declare a class Serializable if this is not the case. The error will be detected at runtime.

During deserialization, the fields of non-serializable classes will be initialized using the public or protected no-arg constructor of the class. A no-arg constructor must be accessible to the subclass that is serializable.

Problem

In interview it was ask that there is a Class `A` which does not implement the `serializable` interface as shown below ``` class A { private int a; A( int a) { this.a = a; } } ``` and there is a class `B` which extends `A` and also implements the `serializable` interface ``` class B extends A implements serializable { private int a , b; B(int a, int b) { this.a = a; this.b = b; } } ``` Now please advise whether I can serialize class `B` or not , provided that class `A` is not serialized suppose I want to serialize the object of class `B`, can it be done.

Original source