Object Serialization in Java 1.1
Making Objects Persistent
By Chad Darby
Java 1.1 introduces object serialization, an easy-to-use and easy-to-implement data-storage method that eliminates worries about file formats. Object serialization lets you save an object's state, thereby saving the values of the data members and functionality of the methods. In effect, this provides object "persistence." Say, for example, you are writing a computer game with a save option. If the player's state information -- position, score, and so on -- is maintained in a game object, you can simply serialize that object to a disk file. The serialization will recursively save all objects pointed to by the game object; then, when the player restarts the game, only the game object must be reloaded.
In this article we will step through object serialization using a simple class, then focus on its implementation in a real-world application. (For more on object serialization, see Bruce Eckel's July 1997 "Java Alley" column in Web Techniques.)
Customer Class Design
To illustrate serializing an object, we will use a simple Customer class that holds a customer's name and age; see
Figure 1. The class will override the toString() method to provide a string representation; however, the real meat of this example will be in the load() and save() methods, which provide the actual code for reading and writing serialized objects.<>