Java Reference
In-Depth Information
explain the effect of the
Serializable
interface a bit later in this chapter, but first let's
see how you do binary file I/O with a serializable class, such as this class
SomeClass
in
Display 10.18 .
Display 10.19 illustrates how class objects can be written to and read from a binary
file. To write an object of a class such as
SomeClass
to a binary file, simply use the
method
writeObject
of the class
ObjectOutputStream
. You use
writeObject
in the
same way that you use the other methods of the class
ObjectOutputStream
, such as
writeInt
, but you use an object as the argument.
If an object is written to a file with
writeObject
, then it can be read back out of
the file with
readObject
of the stream class
ObjectInputStream
, as also illustrated in
Display 10.19 . The method
readObject
returns its value as an object of type
Object
.
If you want to use the values retuned by
readObject
as an object of a class such as
SomeClass
, you must do a type cast, as shown in Display 10.19.
writeObject
readObject
The
Serializable
Interface
A class that implements the
Serializable
interface is said to be a
serializable
class. To
use objects of a class with
writeObject
and
readObject
, that class must be serializable.
But to make the class serializable, we change nothing in the class. All we do is add
the phrase
implements Serializable
. This phrase tells the run-time system that it
is OK to treat objects of the class in a particular way when doing file I/O. If a class is
serializable
Display 10.18
A Serializable Class
1
import
java.io.Serializable;
2
public class
SomeClass
implements
Serializable
3 {
4
private int
number;
5
private char
letter;
6
public
SomeClass()
7 {
8 number = 0;
9 letter = 'A';
10 }
11
public
SomeClass(
int
theNumber,
char
theLetter)
12 {
13 number = theNumber;
14 letter = theLetter;
15 }
16
public
String toString()
17 {
18
return
"Number = " + number
19 + " Letter = " + letter;
20 }
21 }