Search code examples
javaserializationmarker-interfaces

Why class need to implement serializable marker interface for serialization?


Techincally i know why class need to implement serializable . Reason is writeObject method of ObjectOutputStream internally checks the "instance of serializable" before writing the state of object.

But my question is what is the need of that? writeObject method can simply write the object state whether object (whose state needs to be written ) implements serializable or not?

As per wiki ,a class implements this interface to indicate that its non-transient data members can be written to an ObjectOutputStream. But again question is why class needs to implement serializable just to determine whether field is transient or not. Even a class that does not implement serialiable should be serialized (except the fields marked as transient).

Marking an object as serializable (with an interface) doesn't magically make that object serializable, it was serializable all along, it's just that now you expressed something that the system could have found on his own, so I see no real good reason for serialization being the way it is now.

Why class need to implement serializable marker interface to serialize the class?


Solution

  • By providing the marker interface, people can choose whether to make a class Serializable. Sometimes, you might not want this! (and certainly, it would not be good to make this the default: See for example the answers to this question: Why Java needs Serializable interface?)