Reading serialized java object from a file.

You can build an java.io.ObjectInputStreamfrom any
java.io.InputStream.

Beware of creating an java.io.ObjectInputStream from a stream which does not contain
a serialized object, will result in a java.io.StreamCorruptedException.

java.io.ObjectInputStream's readObject() method returns an
java.lang.Object so you have to downcast
the object to the appropriate class.
(for the last you should catch the java.lang.ClassCastException)

Unmarshalling an object involves assemling the object from its component elements,
which will be:

If the object has been read from the stream already,
the reference to the existing object is returned

First, the java.io.ObjectStreamClass
is read ( includes verifying the serialVersion)

The no-argument constructor of the first non-serializable superclass is called

Primitive data members are set directly from the stream
(No serializable class constructor is called and fields initializers are also ignored)

Any reference data members (instances of other classes) are deserialized recursively.

Static and transient fields will not be deserialized as de are not serialized.

Since reference data (object members) must also be sent, they must also implement Serializable.

Read an object - example:

First a class, Rectangle, that is made serializable (same as in previous session):