Saving Objects — Chapter 14

Steps in writing a serialized object to a file

Serialization saves the entire object graph (all objects referenced by instance variables, starting with the object being serialized)

  1. Make a FileOutputStream
  2. Make an ObjectOutputStream
  3. Write the object
  4. Close the ObjectOutputStream

Connection Stream

A connection to a source or destination (file, socket etc.) while chain streams can’t connect on their own and must be channeled to a connection stream.

Steps in making an object deserialized

  1. Object on the heap
  2. Object serialized

Facts about saving objects using Java

  1. You can save an object’s state by serializing the object.
  2. To serialize an object, you need an ObjectOutputStream (from the java.io package)
  3. Streams are either connection streams or chain streams
  4. Connection streams can represent a connection to a source or destination, typically a file, network socket connection, or the console.
  5. Chain streams cannot connect to a source or destination and must be chained to a connection (or other) stream.
  6. To serialize an object to a file, make a FileOuputStream and chain into an ObjectOutputStream.
  7. To serialize an object, call writeObject(theObject) on the ObjectOutputStream. You do not need to call methods on the FileOutputStream.
  8. To be serialized. an object must implement the Serializable interface. If a superclass of the class implements Serializable, the subclass will automatically be serializable even if it does not specifically declare/ implements Serializable.
  9. When an object is serialized, its entire object graph is serialized. That means any objects referenced by the serialized object’s instance variables are serialized, and any objects referenced by those objects…and soon.
  10. If any object in the graph is not serializable, an exception will be thrown at runtime, unless the instance variable referring to the object is skipped.
  11. Mark an instance variable with the transient keyword if you want serialization to skip that variable. The variable will be restored as null (for object references) or default values (for primitives).
  12. During deserialization, the class of all objects in the graph must be available to the JVM.
  13. You read objects In (using readObjeet()) in the order in which they were originally written.
  14. The return type of readObjectO is type Object, so deserialized objects must be cast to their real type.
  15. Static variables are not serialized it doesn’t make sense to save a static variable value as part of a specific object’s state. since all objects of that type share only a single value.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Upulie Handalage

Upulie Handalage

Everything in my point of view. Here for you to read on....