I've been learning how to use Serializable
.
I know if I create a class 'A' with different variables who implements Serializable
and I add Serializable
to my class, it's also Serializable
.
But, who is actually implementing those two methods to serialize?
Does Object
take care of everything or different classes overloads them when necessary?
The serialization is actually implemented in java.io.ObjectOutputStream
(and java.io.ObjectInputStream) and some of its helper classes. In many cases, this built-in support is sufficient, and the developer simply needs to implement the marker interface Serializable
. This interface is called a "marker" because it doesn't declare any methods, and thus doesn't require any special API on implementation classes.
A programmer can add or replace default serialization mechanism with their own methods if needed. For example, if some additional initialization is required after deserializing an object, a method can be added with the following signature:
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, java.lang.ClassNotFoundException
For total control over serialization and deserialization, implement java.io.Externalizable
instead of Serializable
.
There are many other extension points in Java serialization, if needed. The serialization specification is an authoritative and complete source for learning about all of them.