Java Reference
In-Depth Information
Being serializable can be quite simple. The default serialization process
is to serialize each field of the object that is neither
TRansient
nor
static
. Primitive types and strings are written in the same encoding
used by
DataOutputStream
; objects are serialized by calling
writeObject
.
With default serialization, all serialized fields that are object references
must refer to serializable object types. Default serialization also requires
either that your superclass have a no-arg constructor (so that deserializ-
ation can invoke it) or that it also be
Serializable
(in which case declar-
ing your class to implement
Serializable
is redundant but harmless). For
most classes this default serialization is sufficient, and the entire work
necessary to make a class serializable is to mark it as such by declaring
that it implements the
Serializable
interface:
public class Name implements java.io.Serializable {
private String name;
private long id;
private transient boolean hashSet = false;
private transient int hash;
private static long nextID = 0;
public Name(String name) {
this.name = name;
synchronized (Name.class) {
id = nextID++;
}
}
public int hashCode() {
if (!hashSet) {
hash = name.hashCode();
hashSet = true;
}
return hash;
}
// ... override equals, provide other useful methods
}