Ch 14: Saving Objects
Source: Head First Java, Second Edition | Pages: 463-504
🎯 Learning Objectives
Serialization and File I/O
📚 Key Concepts
Serialization concept
ObjectOutputStream
ObjectInputStream
Serializable interface
transient keyword
File I/O
Saving and loading objects
Version control for serialized classes
📖 Detailed Notes
1. Serialization concept
Essential concept for mastering Java and OOP.
Example:
2. ObjectOutputStream
Essential concept for mastering Java and OOP.
Example:
3. ObjectInputStream
Essential concept for mastering Java and OOP.
Example:
4. Serializable interface
Essential concept for mastering Java and OOP.
Example:
5. transient keyword
Essential concept for mastering Java and OOP.
Example:
6. File I/O
Essential concept for mastering Java and OOP.
Example:
7. Saving and loading objects
Essential concept for mastering Java and OOP.
Example:
8. Version control for serialized classes
Essential concept for mastering Java and OOP.
Example:
💡 Important Points to Remember
that the Dog
those flashcards you used in school? Where you
split() is FAR more powerful than
✅ Self-Check Questions
Test your understanding:
Can you explain the main concepts covered in this chapter?
Can you write code examples demonstrating these concepts?
Do you understand when and why to use these features?
Can you explain the benefits and tradeoffs?
🔄 Quick Revision Points
📝 Practice Exercises
Write your own code examples for each key concept
Modify existing examples to test edge cases
Explain concepts to someone else
Create a small project using these concepts
🔗 Related Chapters
Review related concepts from other chapters to build comprehensive understanding.
For complete details, diagrams, and all examples, refer to Head First Java Second Edition, pages 463-504.
Chapter 14: Saving Objects — Study Notes
This chapter focuses on data persistence—saving the state of your program so it can be reloaded later. It covers two main approaches: Serialization (saving whole objects) and File I/O (writing data to text files).
1. Serialization (Saving Objects)
Serialization is the process of "flattening" an object into a stream of bytes so it can be stored in a file or sent over a network. When you serialize an object, you save its state (instance variables).
The Serialized File
What it is: A file containing the serialized bytes of an object.
Readability: It is not human-readable text; it's a binary format understood by the Java Virtual Machine (JVM).
How to Serialize
To make an object serializable, its class must implement the Serializable interface.
Interface:
java.io.SerializableMarker Interface: It has no methods to implement. It serves only as a "stamp" to tell the JVM, "It's okay to serialize objects of this type."
Java
The Object Graph
When an object is serialized, the JVM saves everything that object refers to.
Cascading Save: If a
Dogobject has aCollarinstance variable, serializing theDogautomatically serializes theCollar. If theCollarhas aColorobject, that gets saved too.Requirement: All objects in the graph must be
Serializable. If any object in the chain is notSerializable, aNotSerializableExceptionis thrown at runtime.
Skipping Variables: transient
transientIf a variable should not (or cannot) be saved, mark it as transient. The serialization process will skip it, and when the object is restored, that variable will return as null (or the default primitive value).
Java
2. Deserialization (Restoring Objects)
Deserialization is the reverse process: reading the bytes from a file and inflating them back into a living Java object on the heap.
Steps to Restore
Open File:
FileInputStream fileStream = new FileInputStream("MyGame.ser");Make ObjectStream:
ObjectInputStream os = new ObjectInputStream(fileStream);Read Object:
Object one = os.readObject();Cast: The return type is
Object, so you must cast it back to your specific type (e.g.,GameCharacter elf = (GameCharacter) one;).Close:
os.close();.
Key Rules of Restoration
Class Found: The JVM must be able to find the class file for the object. If the class is missing, deserialization fails.
Constructors:
The constructor for the serialized object is NOT run. (This preserves the object's saved state rather than resetting it).
However, if a superclass in the hierarchy is not serializable, its constructor will run.
Static Variables: Static variables are not saved because they belong to the class, not the object. When an object is deserialized, it sees whatever static value the class currently has.
3. Writing to Text Files
Sometimes you need to write data that other programs (like Notepad or Excel) can read. For this, you write plain text files.
The java.io.File Class
java.io.File ClassPurpose: Represents a file on the disk, but not the content of the file. It’s an abstract path representation.
Capabilities:
Make a new directory:
dir.mkdir()List files in a directory:
if (dir.isDirectory()) { String[] dirContents = dir.list(); }Get absolute path:
dir.getAbsolutePath()Delete a file or directory:
didItWork = myFile.delete()
Writers and Readers
Writing: Use
FileWriterto write characters to a file.Java
Buffers: For efficiency, wrap your
FileWriterin aBufferedWriter. This reduces the number of trips to the disk by holding data in memory until the buffer is full.Java
4. Reading from Text Files
To read a text file, the standard approach involves chaining streams to parse the text line-by-line.
The Chain
File: Represents the file on disk.FileReader: Connects to the text file.BufferedReader: Reads text efficiently and allows reading one line at a time.
Java
Parsing Strings
split(): A method in theStringclass that breaks a string into an array of pieces (tokens) based on a delimiter.Java
5. serialVersionUID
serialVersionUIDVersioning: Every time you change a class (e.g., add a method), the class gets a new unique "version ID".
The Conflict: If you serialize an object (ID: 100), change the class (ID: 101), and then try to deserialize the old object, the JVM will throw an exception because the IDs don't match.
The Fix: You can manually define a
static final long serialVersionUIDin your class. This tells the JVM, "Trust me, this version of the class is compatible with the old serialized objects," preventing the crash even if you've made changes to the class methods.
6. Revision Checklist
Connection vs. Chain Streams: Remember that "Connection" streams (like
FileOutputStream) connect to a source/destination, while "Chain" streams (likeObjectOutputStream) perform high-level processing (like serialization).Closing: Always close your streams! Closing the top-level chain stream automatically closes the underlying connection stream.
Buffers: Use
BufferedWriterandBufferedReaderfor better performance when working with text files.Transient: Use
transientfor sensitive data (like passwords) or nonserializable object references (like network sockets) that shouldn't be saved.
Last updated