Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If my class implements Serializable, do I have to implement it in its subclasses?

If I have B extends A... and A implements Serializable, do I have to write "B implements Serializable" ?

I think no, but I would like confirmation...

also if I put serialization id in A... do I need to put one in B also ? should serialization id in A be protected (not private) ?

like image 296
ycomp Avatar asked Feb 04 '12 16:02

ycomp


People also ask

Do subclasses need to implement Serializable?

Yes. Subclass need not be marked serializable explicitly.

What happens if a class implements Serializable?

If a super class implements Serializable, then its sub classes do automatically. When an instance of a serializable class is deserialized, the constructor doesn't run. If a super class doesn't implement Serializable, then when a subclass object is deserialized, the super class constructor will run.

Do subclasses inherit Serializable?

If the superclass is Serializable, then by default, every subclass is serializable. Hence, even though subclass doesn't implement Serializable interface( and if its superclass implements Serializable), then we can serialize subclass object.

Is it necessary to implement Serializable in entity?

If an entity instance is to be passed by value as a detached object (e.g., through a remote interface), the entity class must implement the Serializable interface. In practice, if our object is to leave the domain of the JVM, it'll require serialization. Each entity class consists of persistent fields and properties.


1 Answers

Yes. Subclass need not be marked serializable explicitly.

And, marking id as protected will do (from compiler perspective).

But, as good practice every class should have it's own private serialVersionUID.

like image 71
Azodious Avatar answered Sep 18 '22 21:09

Azodious