Why should classes designed for inheritance rarely implement the Serializble interface?

According to efficient Java:

Classes intended for inheritance should rarely use Serializable, and interfaces should rarely extend it.

What is the reason for this statement? In other words, what would be the problem if they implemented the Serializable interface?

+8
java inheritance serialization
source share
3 answers

The following sentence in the same paragraph says:

Classes intended for inheritance (clause 17) should rarely implement Serializable, and interfaces should rarely extend it. Violation of this rule imposes a significant burden on everyone who extends the class or implements the interface. There are times when you need to break the rule. For example, if a class or interface exists mainly to participate in a structure that requires all participants to implement Serializable, then for a class or interface it makes sense to implement or extend Serializable.

Since I don't want Josh to be on my tail to infringe on copyright (no matter how cool it is), I would not copy the whole element in this answer. Suffice it to say that the reasoning for this is explained in the rest of the subject.

EDIT: Josh listed a number of costs for implementing Serializable . If an interface / superclass implements it, the costs will be forcibly transferred to expanding classes.

The main cost of implementing Serializable is that it reduces the flexibility to change the implementation of classes after it has been released ....

...

The second cost of implementing Serializable is that it increases the likelihood of errors and security holes ....

The third cost of implementing Serializable is that it increases the test burden associated with the release of a new version of the class.

+7
source share

If the base class or interface implements Serializable, it forces each subclass or implementation to execute a contract on the superclass or interface to ensure that the subclass or implementation is also serializable.

This prevents any implementation from adding fields that are not temporary and cannot be serialized to implement them, for example.

+7
source share

All subtypes of a serializable class are themselves serializable, as indicated here . So if you are going to serialize a class intended for inheritance, you should know all subclasses are necessary for serialization. Otherwise, you can serialize only the necessary subclass.

0
source share

All Articles