So far, we’ve focused on the mechanics of serializing an object. We’ve assumed we have a serializable object and discussed, from the point of view of client code, how to serialize it. The next step is discussing how to make a class serializable.
There are four basic things you must do when you are making a class serializable. They are:
Make sure that instance-level, locally defined state is serialized properly.
Make sure that superclass state is serialized properly.
Let’s look at each of these steps in more detail.
This is by far the
easiest of the steps. The
Serializable interface is an empty
interface; it declares no methods at all. So
implementing it amounts to adding “implements
Serializable” to your class declaration.
Reasonable people may wonder about the
utility of an empty interface. Rather than define
an empty interface, and require class definitions
to implement it, why not just simply make every
object serializable? The main reason not to do
this is that there are some classes that don’t
have an obvious serialization. Consider, for
example, an instance of
File. An instance of
File represents a file.
Suppose, for example, it was created using the
following line of code:
File file = new File("c:\\temp\\foo");
It’s not at all clear what should be written out when this is serialized. The problem is that the file itself has a different ...