Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the rationale behind "Serializable" interface? [duplicate]

If we want to serialize an object, we can simply do the following implementation:

class MyClass implements Serializable
{
  private static final long serialVersionUID = 12345L;
}

And no extra effort is needed to imperatively implement how the object will be written into and read from files. Java simply takes care of everything.

On the other hand, Externalizable does define explicit serialization and deserialization methods so we can program imperatively.

This leaves me the question: if no extra effort is needed for Serializable, what's the rationale to make it an interface that we have to implement to serialize/deserialize objects, instead of making it by default that every object can be serialized/deserialized?

like image 731
OneZero Avatar asked Feb 04 '26 15:02

OneZero


1 Answers

When a programmer marks a class as Serializable he takes responsibility that if this class will change in future, programs which saved objects will be able to read them back to the updated class. Details are in Effective Java Item 74: Implement Serializable judiciously

There is another rationale. Did you ever notice that ObjectOutput.writeObject(Object obj) accepts Object, not Serializable? This is because it assumes that objects may be saved using different serialization mechanizms. Serializable means that object is supposed to be saved using Java standard serialization

like image 188
Evgeniy Dorofeev Avatar answered Feb 06 '26 06:02

Evgeniy Dorofeev