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?
Yes. Subclass need not be marked serializable explicitly.
In order to prevent subclass from serialization we need to implement writeObject() and readObject() methods which are executed by JVM during serialization and deserialization also NotSerializableException is made to be thrown from these methods.
It'll throw a NotSerializableException when you try to Serialize it. To avoid that, make that field a transient field.
No. If you want to serialise an object it must implement the tagging Serializable interface.
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 Always!
Consider this:
public class Parent implements Serializable { private int i; // ... } public class Child extends Parent { private final 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
.
(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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With