Java Reference
In-Depth Information
Q: Does it send them in a specific order?
A: To be honest, the order doesn't matter. The JVM handles all the
details of serialization and deserialization. The implementation
details are discussed in the Java Language Specification, if you are
interested in the seeing exactly how the process works behind the
scenes.
Q: Can I serialize any Object in Java?
A: No. You can only serialize objects that are serializable . An Object
is serializable if its class implements the java.io.Serializable inter-
face. This interface does not contain any methods. It simply tags
the class so instances of the class can be serialized.
Q: If you don't have to write any extra methods to make a class serial-
izable, why didn't Sun just make all classes serializable by default?
A: Two reasons: It does not make sense to serialize some classes
because their state is not something that can be saved and recre-
ated. The Thread class is a good example of a class that is not seri-
alizable. It really does not make sense to serialize a thread and
then deserialize it later. For the same reason, none of the stream
classes in the java.io package are serializable. Also, implementing
Serializable allows you to decide, from a design point of view, if
you want instances of your classes to be serialized or not.
Q: Why would you not want a class to be serializable, assuming that
it makes sense to serialize its fields?
A: Well, you probably do want most of your classes to be serializable.
In most situations, if you write a class whose state can be main-
tained, you will make it serializable for the benefit of others using
the class. You might have a class, however, that contains sensitive
data that you do not want anyone to ever serialize.
Q: What if you want some of the fields of a class to be serializable,
but not all them?
A: You can mark a particular field as transient, a keyword in Java, so
that it will be ignored during serialization. There are also situations
in which the transient keyword must be used for fields that are not
serializable. For example, if a serializable class has a Thread field,
the field must be marked as transient or a java.io.NotSerializable-
Exception will occur if an attempt is made to serialize the object.
Q: What will the value be of a transient field when the object is
deserialized?
A: Transient fields have a zero value when they are deserialized. For
example, numeric types will be 0 and references will be null.
Search WWH ::




Custom Search