How Object Serialization Works

Objects possess state. This state is stored in the values of the nonstatic, nontransient fields of an object’s class. Consider this TwoDPoint class:

public class TwoDPoint {
  public double x;
  public double y;
}

Every object of this class has a state defined by the values of the double fields x and y. If you know the values of those fields, you know the value of the TwoDPoint. Nothing changes if you add some methods to the class or make the fields private, as in Example 11.1.

Example 11-1. The TwoDPoint Class

public class TwoDPoint {
  private double x;
  private double y;

  public TwoDPoint(double x, double y) {
    this.x = x;
    this.y = y;
  }

  public double getX() {
    return x;
  }

  public double getY() {
    return y;
  }
  
  public void setX(double x) {
    this.x = x;
  }

  public void setY(double y) {
    this.y = y;
  }
  
  public String toString() {
    return "[TwoDPoint:x=" + this.x + ", y=" + y +"]";
  }
}

The object information, the information stored in the fields, is still the same. If you know the values of x and y, you know everything there is to know about the state of the object. The methods only affect the actions an object can perform. They do not change what an object is. Now suppose you wanted to save the state of a particular point object by writing a sequence of bytes onto a stream. This process is called serialization, since the object is serialized into a sequence of bytes. You could add a writeState() method to your class that looked something like this:

public void writeState(OutputStream ...

Get Java I/O now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.