1

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;}
    }

1 Answer 1

4

BB has a field of type A, and A does not implement Serializable. In a serializable class, the types of all fields must be serializable, as must the types of the fields of those types, and so on.


Alternatively (although you probably don't want this), you can use the transient keyword to declare the field to be excluded from serialization:

transient A aInstance = new A();

If you do this, aInstance will be null when a B or BB instance is deserialized, even if the field was non-null when the instance was serialized.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.