Java Reference
In-Depth Information
The
Console
class is preferred over using
System.out
and
System.in
when working with formatted output to the console or console input from
the user. Because the class is new in Java 6.0, expect a question or two
about
Console
on the exam.
Next we discuss a different exam objective: object serialization. I explain how it works
in the next section and discuss the various classes and interface involved.
Object Serialization
The exam objectives state that you need to be able to “develop code that serializes and/or
de-serializes objects using the following APIs from
java.io
:
DataInputStream
,
DataOutput-
Stream
,
FileInputStream
,
FileOutputStream
,
ObjectInputStream
,
ObjectOutputStream
and
Serializable
.” In other words, you need to understand the details of Java object seri-
alization. The earlier section titled “The DataInputStream and DataOutputStream Classes”
discussed saving the state of an object using
DataInputStream
and
DataOutputStream
. This
section focuses on the
ObjectInputStream
and
ObjectOutputStream
classes and the
Serial-
izable
interface.
Object serialization
refers to taking the state of an object and writing it to a stream.
You can use serialization to persistently store your objects in fi les. You can also serial-
ize an object and send it across the network to another Java program or save it in a data-
base.
Deserialization
refers to the process of reading the data from an object stream and
reconstituting the object in memory. Not all objects can be serialized; only objects whose
classes implement the
java.io.Serializable interface
. Let's take a look at this interface
and what it means to implement it.
The
Serializable
Interface
The
Serializable
interface is a tagging interface, which means it does not have any meth-
ods in it. A class implements
Serializable
to let the JVM know that instances of the class
can be serialized. There is no extra work on your part to make a class serializable because
there are no methods in the interface. Your main concern with implementing
Serializ-
able
is ensuring that all the fi elds in your class are also
Serializable
. If an attempt is
made to serialize an object and a fi eld is reached during the serialization process that is not
serializable, the JVM throws a
NotSerializableException
and the serialization fails. The
compiler does not verify whether or not your fi elds are
Serializable
. Denote a fi eld as
transient
(using the
transient
keyword) to tell the JVM to ignore the fi eld during the seri-
alization and deserialization process.
Search WWH ::
Custom Search