Java Reference
In-Depth Information
Why Not Make Everything Serializable?
You might be wondering why Java doesn't just make all objects serializable automatically.
The reason is that for some objects it does not make sense to save their state. For
example, the Thread class is not serializable, nor are any of the stream classes in the java.
io package. It would be too diffi cult to try to save the state of a thread or stream object,
and their state is often not the kind of information that you want or need to save anyway.
However, most classes in the Java API are serializable and many of the classes you write
will likely be serializable as well. For example, the String class implements Serializable ,
as do most of the data structure classes in the Collections API of the java.util
package. If you are not sure whether or not an object is serializable, check the Java API
documentation and see if its corresponding class implements the Serializable interface.
Let's take a look at an example by revisiting the Contact class from earlier in this chap-
ter. I renamed the class Contact2 to distinguish it from the earlier version, and I added a
GregorianCalendar fi eld to represent the person's birthday. The Contact2 class implements
Serializable , and I also made the fi elds private to demonstrate that the access specifi er
on a fi eld does not have an effect on serialization. The city fi eld is declared transient to
demonstrate the effect of the transient keyword.
package com.sybex.io;
import java.util.GregorianCalendar;
public class Contact2 implements java.io.Serializable {
private String name;
private int age;
private long cellPhone;
private GregorianCalendar birthday;
private transient String city;
public Contact2(String name, int age, long cellPhone,
GregorianCalendar birthday, String city) {
this.name = name;
this.age = age;
this.cellPhone = cellPhone;
this.birthday = birthday;
this.city = city;
}
public String toString() {
Search WWH ::




Custom Search