Page 657 - Introduction to Programming with Java: A Problem Solving Approach
P. 657
15.8 Object File I/O 623
/******************************************************
*
TestObject.java
Dean & Dean
This is a typical heterogeneous object.
******************************************************/
*
*
*
import java.io.*;
public class TestObject implements Serializable
{
}
// end TestObject class
private int id;
private String text;
public double number;
//***************************************************
public TestObject(int id, String text, double number)
{
this.id = id;
this.text = text;
this.number = number;
} // end constructor
Apago PDF Enhancer
//***************************************************
public void display()
{
System.out.print(this.id + "\t");
System.out.print(this.text + "\t");
System.out.println(this.number);
} // end display
To be writable to and readable from a file, an object must be an instance of a class that implements this interface.
Figure 15.10 Typical definition of a Serializable object
Notice the second output in Figure 15.12’s sample session. Can you figure out what happened? The WriteObject program outputs only one object to the objectFile.data file, but the ReadObject pro- gram tries to read two objects from that file. Since it cannot find a second object, the JVM throws an IOException, which generates the print statement in the last output line.
If a class is Serializable, all classes derived from it are automatically Serializable, too. Sup- pose your Serializable class has instance variables that refer to other objects. Those objects’ classes also must be Serializable. This must be true through all levels in a composition hierarchy. Does this soundlikeapain?It’snot,really.Justbesuretoincludeimplements Serializableinthedefinition of all classes that define objects you’d like to store as objects. The alternative would be a pain, though. If you couldn’t store a whole object, you’d have to provide explicit code to write and read each primitive data item
⎫ ⎪ ⎪ ⎬ ⎪ ⎪ ⎭