Java Reference
In-Depth Information
Implementing the Serializable Interface
As I hope you still remember, the fundamental step in making objects serializable is to implement the
Serializable
interface in every class that defines objects we want written to a file. We need a
methodical approach here, so how about top-down - starting with the
SketchModel
class.
Try It Out - Serializing SketchModel Objects
This is where we get a great deal from astonishingly little effort. To implement serialization for the
SketchModel
class you must first modify the class definition header to:
class SketchModel extends Observable implements Serializable {
The
Serializable
interface is defined in the package
java.io
so we need to add an
import
statement to the beginning of the
SketchModel.java
file:
import java.io.Serializable;
The
Serializable
interface declares no methods - so that's it!
Is that enough to serialize a sketch? Not quite. For a class to be serializable, all its data members must
be serializable or declared as
transient
. If this is not the case then an exception of type
NotSerializableException
will be thrown. To avoid this we must trawl through the data elements
of the
SketchModel
class, and if any of these are our own classes we must make sure they either
implement the
Serializable
interface, or are declared as
transient
.
We also must not assume that objects of a standard class type are serializable, because some most
definitely are not. It's a fairly quick fishing trip though, because our
SketchModel
class only has one
data member - the linked list of elements that make up the sketch. If the
SketchModel
object is to be
serializable we simply need to make sure the
elementList
member is serializable.
Serializing the List of Elements
Looking through the javadocs we can see that the
LinkedList
class is serializable, so all we need to
worry about are the list elements themselves. We can make the base class for our shape class,
Element
,
serializable by declaring that it implements the interface:
public abstract class Element implements Serializable {
Don't forget that we now need an
import
statement for the
Serializable
interface in
Element.java
. Since we will be using several classes from the
java.io
package, let's save a few
lines and import all the names into
Element.java
:
import java.io.*;
The data members of the
Element
class that are object references are of type
Color
or of type
Point
,
and since both of these classes are serializable, as you can verify from the SDK documentation, our
Element
class is serializable. Now we need to look at the subclasses of
Element
.