BB is the parent to B. A is a stand-alone class. All I'm doing with this code is writing an object of type B to a file and then reading it back.
The code as shown runs okay. Additionally, we know that if a class is Serializable then its subclasses are automatically Serializable too.
With that in mind, why do I get a NotSerializableException if instead of B being serializable, BB (its parent) is? I would expect the same output in both cases.
public class Main {
public static void main(String[] args) {
B bb = new B();
B bb2 = null;
try(ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("text.ser"));
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("text.ser"))){
oos.writeObject(bb);
bb2 = (B) ois.readObject();
}catch(Exception e){e.printStackTrace();}
}
}
class A {
int a = 1, hello=7;
A() {a = 2;}
}
class BB {
int bb = 1;
A aInstance = new A();
BB() {bb = 2;}
}
class B extends BB implements Serializable{
int b = 1;
B() {b = 2;}
}