Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 775
Benas Avatar asked Sep 04 '14 13:09

Benas


People also ask

Do subclasses need to implement serializable?

Yes. Subclass need not be marked serializable explicitly.

How can subclass avoid serialization?

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.

What happens if your serializable class contains a member which is not serializable?

It'll throw a NotSerializableException when you try to Serialize it. To avoid that, make that field a transient field.

Can we serialize class without implementing serializable interface?

No. If you want to serialise an object it must implement the tagging Serializable interface.


1 Answers

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.)

like image 59
Stephen C Avatar answered Oct 15 '22 19:10

Stephen C