434 chapter 14 Objects on the heap have state—the
value of the object’s instance
variables. These values make one
instance of a class different from
another instance of the same class.
What really happens to an object
when it’s serialized?
Foo myFoo = new Foo(); myFoo.setWidth(37); myFoo.setHeight(70); FileOutputStream fs = new FileOutputStream(“foo.ser”); ObjectOutputStream os = new ObjectOutputStream(fs); os.writeObject(myFoo); 1 Object on the heap
2 Object serialized
serialized objects 00100101
width
01000110
height
00100101
01000110
Serialized objects save the values of the instance variables, so that
an identical instance (object) can be
brought back to life on the heap.
The instance variable values
for width and height are
saved to the file “foo.ser”,
along with a little more info
the JVM needs to restore
the object (like what its
class type is).
foo.ser
Object with two primitive
instance variables.
The values are sucked
out and pumped into
the stream.
Make a FileOutputStream that connects
to the file “foo.ser”, then chain an
ObjectOutputStream to it, and tell the
ObjectOutputStream to write the object.