Java Reference
In-Depth Information
return name + “ “ + age + “ “ + cellPhone;
}
public String getCity() {
return city;
}
}
The Contact2 class implements Serializable , so each of its nontransient fi elds better be
Serializable as well. The primitive types are no problem because all the primitive types
are serializable. You won't be surprised to fi nd that the String class implements Serial-
izable , as does the GregorianCalendar class. Therefore, we should be able to serialize
objects of type Contact2 using the ObjectOutputStream class.
The ObjectOutputStream Class
An ObjectOutputStream writes Serializable objects to an output stream. It is a high-level
stream that needs to be chained to a low-level stream that represents the destination of the
serialized objects. The upcoming SerializeDemo program demonstrates using FileOutput-
Stream with ObjectOutputStream .
The ObjectOutputStream class contains methods for writing primitive types and
String objects, but the principal method of ObjectOutputStream is public void
writeObject(Object obj) throws IOException .
The writeObject method serializes the Object argument passed in. If the Object passed
in is not serializable, a NotSerializableException is thrown. If the Object is serializable,
all the information necessary to deserialize the object is written to the stream, including the
class name, class signature, and the values of the nonstatic and nontransient fi elds.
Let's look at an example that serializes Contact2 objects to a fi le. Study the following
SerializeDemo program and see if you can determine its result:
1. package com.sybex.io;
2.
3. import java.io.*;
4. import java.util.GregorianCalendar;
5.
6. public class SerializeDemo {
7. public static void main(String [] args) {
8. try {
9. GregorianCalendar bday1 =
10. new GregorianCalendar(1950, 3, 21);
11. GregorianCalendar bday2 =
12. new GregorianCalendar(1956, 5, 30);
13. Contact2 one = new Contact2(“Bugs Bunny”, 22,
Search WWH ::




Custom Search