Search code examples
javaserialization

Is a subclass of a "Serializable" class automatically "Serializable"?


Does a child class of a class that implements the Serializable interface also implement Serializable? In other words, can instances of the child class also be serialized?


Solution

  • I wanted to ask whether the child of the parent, which implements "Serializable" interface, implements "Serializable" interface too, or in other words can that child be serialized?

    The answer to the first part is Yes. It is a natural consequence of Java inheritance.

    The answer to the second part ("in other words ...") is Not Always1!

    Consider this:

    public class Parent implements Serializable {
        private int i;
        // ...
    }
    
    public class Child extends Parent {
        private Thread t = new Thread();   // a non-serializable object
        // ...
    }
    

    An instance of Parent can be serialized, but an instance of Child cannot ... because it has an attribute whose type (Thread) does not implement Serializable. If you attempt to serialize a Child instance with a non-null t field, you will get an exception.

    Now if t was declared as transient, or if Child avoided using the default serialization mechanism, Child could be made to be serializable. But my point is that serializability is an emergent property, not an inheritable property.


    1 - This is notwithstanding what you think that the javadocs say!