Java Reference
In-Depth Information
To demonstrate how serialization works in Java, I am going to use the
Employee class that we discussed early on in the topic. Suppose that we have
the following Employee class, which implements the Serializable interface:
public class Employee implements java.io.Serializable
{
public String name;
public String address;
public int transient SSN;
public int number;
public void mailCheck()
{
System.out.println(“Mailing a check to “ + name
+ “ “ + address);
}
}
The fields in the Employee class are public just to simplify this example;
however, if they were private, they would be serialized in the same
manner. The access specifier of a field has no effect on serialization.
The SSN field of Employee is transient to demonstrate what happens to
transient fields during serialization. Notice that for a class to be serialized suc-
cessfully, two conditions must be met:
The class must implement the java.io.Serializable interface.
■■
All of the fields in the class must be serializable. If a field is not serializ-
able, it must be marked transient.
■■
Employee objects will be successfully serialized because its nontransient
fields (one int and two String references) are serializable. Note that the String
class is serializable, as are all eight primitive data types. The Employee class is
ready to be serialized, so let's look at how to do this.
If you are curious to know if a class is serializable or not, check the
documentation for the class. The test is simple: If the class implements
java.io.Serializable, then it is serializable; otherwise, it's not. In the
documentation for String, the class is declared as:
public final class String extends Object
implements Serializable, Comparable, CharSequence
Therefore, the String class is serializable. You will find that many of the
classes in the J2SE API are serializable.
Search WWH ::




Custom Search