23.07.2013 Views

Java IO.pdf - Nguyen Dang Binh

Java IO.pdf - Nguyen Dang Binh

Java IO.pdf - Nguyen Dang Binh

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

<strong>Java</strong> I/O<br />

Every object of this class has a state defined by the values of the double fields x and y. If you<br />

know the values of those fields, you know the value of the TwoDPoint. Nothing changes if<br />

you add some methods to the class or make the fields private, as in Example 11.1.<br />

Example 11.1. The TwoDPoint Class<br />

public class TwoDPoint {<br />

private double x;<br />

private double y;<br />

}<br />

public TwoDPoint(double x, double y) {<br />

this.x = x;<br />

this.y = y;<br />

}<br />

public double getX() {<br />

return x;<br />

}<br />

public double getY() {<br />

return y;<br />

}<br />

public void setX(double x) {<br />

this.x = x;<br />

}<br />

public void setY(double y) {<br />

this.y = y;<br />

}<br />

public String toString() {<br />

return "[TwoDPoint:x=" + this.x + ", y=" + y +"]";<br />

}<br />

The object information, the information stored in the fields, is still the same. If you know the<br />

values of x and y, you know everything there is to know about the state of the object. The<br />

methods only affect the actions an object can perform. They do not change what an object is.<br />

Now suppose you wanted to save the state of a particular point object by writing a sequence<br />

of bytes onto a stream. This process is called serialization, since the object is serialized into a<br />

sequence of bytes. You could add a writeState() method to your class that looked<br />

something like this:<br />

public void writeState(OutputStream out) throws <strong>IO</strong>Exception {<br />

DataOutputStream dout = new DataOutputStream(out);<br />

dout.writeDouble(x);<br />

dout.writeDouble(y);<br />

}<br />

To restore the state of a Point object, you could add a readState() method like this:<br />

public void readState(InputStream in) throws <strong>IO</strong>Exception {<br />

DataInputStream din = new DataInputStream(in);<br />

this.x = din.readDouble();<br />

this.y = din.readDouble();<br />

}<br />

240

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!