Java Reference
In-Depth Information
42
numbers[0] = 0.20540865153372645
numbers[1] = 0.14819027494615766
numbers[2] = 0.966333475583602
obj3:
Flies light on lean horses.
42
numbers[0] = 0.582505845190295
numbers[1] = 0.7568767131705605
numbers[2] = 0.031276131457401934
numbers[3] = 0.22867560732800996
numbers[4] = 0.030591566057953434
You should get something vaguely similar.
How It Works
You first create three objects of type Junk in the main() method .Within the try block you create the
ObjectOutputStream object that you use to write objects to the file D:/Junk/JunkObjects.bin via a
buffered output stream. Each Junk object is written to the file by passing it to the writeObject() meth-
od for the ObjectOutputStream object. Each object is written to the file, including the values of its three
instance fields, answer , thought , and numbers . The String object and the array are written to the file as
objects. This is taken care of automatically and requires no special provision within the code. The static
field generator is not written to the file.
The stream is closed automatically at the end of the try block. You read the objects back from the file a
little later in this chapter.
Conditions for Serialization
In general, you could encounter a small fly in the ointment. For implementing the Serializable interface
to be sufficient to make objects of the class serializable, all the fields in the class must be serializable (or
transient — which I come to), and all superclasses of the class must also be serializable. This implies that
the fields must be either of primitive types or of class types that are themselves serializable.
If a superclass of your class is not serializable, it still might be possible to make your class serializable.
The conditions that must be met for this to be feasible are:
• Each superclass that is not serializable must have a public no-arg constructor — a constructor with
no parameters.
• Your class must be declared as implementing the Serializable interface.
• Your class must take responsibility for serializing and deserializing the fields for the superclasses
that are not serializable.
This is usually the case for your own classes, but one or two classes that come along with Java do not
implement the Serializable interface. What's more, you can't make them serializable because they do not
have a public default constructor. The Graphics class in the package java.awt is an example of such a class
— you see more of this class when you get into programming using windows. All is not lost, however. You
have an escape route. As long as you know how to reconstruct any fields that were not serializable when
Search WWH ::




Custom Search