O'Reilly logo

Java RMI by William Grosso

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

How to Make a Class Serializable

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:

  1. Implement the Serializable interface.

  2. Make sure that instance-level, locally defined state is serialized properly.

  3. Make sure that superclass state is serialized properly.

  4. Override equals( ) and hashCode( ).

Let’s look at each of these steps in more detail.

Implement the Serializable Interface

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required