12.2. Summary
In this chapter you have explored how you can write objects to a file and read them back. Making your class serializable makes it very easy to save your application data in a file. While what I have discussed is by no means exhaustive, you now know enough to deal with straightforward object serialization. The important points in this chapter are:
To make objects of a class serializable the class must implement the Serializable interface.
If a class has a superclass that does not implement the Serializable interface, then the superclass must have a public default constructor if it is to be possible to serialize the class.
Objects are written to a file using an ObjectOutputStream object and read from a file using and ObjectInputStream object.
Objects are written to a file by calling the writeObject() method for the ObjectOutputStream object corresponding to the file.
Objects are read from a file by calling the readObject() method for the ObjectInputStream object corresponding to the file.
When necessary—for example, if a superclass is not serializable—you can implement the readObject() and writeObject() methods for your classes.
Get Ivor Horton's Beginning Java™ 2, JDK™ 5th Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.