O'Reilly logo

Ivor Horton's Beginning Java™ 2, JDK™ 5th Edition by Ivor Horton

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

21.2. 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 you want written to a file. You need a methodical approach here, so how about top-down—starting with the SketchModel class.

Try It Out: Serializing SketchModel Objects

This is where you 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 Iterable<Element>, Serializable {

The Serializable interface is defined in the java.io package, so you need to add the following import statement to the beginning of the SketchModel.java file:

import java.io.Serializable;

The Serializable interface declares no methods—so that's it so far as the SketchModel class is concerned!

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 when you try to serialize an object. To avoid this you must trawl through the data elements of the SketchModel class, and if any of these are your own classes, you must make sure they either implement the Serializable interface or are declared as transient.

You also cannot assume that objects of a standard class type are serializable ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required