Programming and Problem Solving with Java

(やまだぃちぅ) #1

(^68) | Java Syntax and Semantics, Classes, and Objects
ClassInputStreamReader
(returns Unicode characters)
ObjectInputStream System.in
(returns bytes)
ClassBufferedReader
(returns a string value)
Figure 2.4 Layering of Classes for Java Input
input a single byte or a series of bytes (recall from Chapter 1 that a byte is eight binary bits).
To be useful to us, this data must be converted to a string.
This problem sounds like a good opportunity to apply means-ends analysis. We look
through the Java library documentation and find a class called BufferedReaderthat provides
a method called readLine, which returns a string that it gets from an object of the class Reader.
However,System.inis an object of the class InputStream. We’re part of the way to our solution;
now we just have to find a way to convert the input from an InputStreamobject so that it acts
like a Readerobject. Further searching in the library reveals a class called InputStreamReader
that does precisely this.
Why do we need to take these steps? What do these conversions actually accomplish?
System.inreturns raw binary bytes of data. An InputStreamReaderconverts these bytes to the
Unicode character set that Java uses. Because we don’t want our input to be in the form of
individual characters, we use a BufferedReaderto convert the characters into a Stringvalue.
Figure 2.4 illustrates this layering of classes.
In Figure 2.4,System.inis an object of the class InputStream—an instance of this class. What
we need is an object of the class InputStreamReader. That is, we need to instantiate an object
of the class InputStreamReader. Earlier we said that we use the newoperator to instantiate ob-
jects. To do so, we write the reserved word new, followed by the name of a class, followed by
an argument list. For example:
InputStreamReader inStream; // A variable of class InputStreamReader
inStream = new InputStreamReader(System.in);
The code following newlooks very much like a method call. In fact, it is a call to a special
kind of method called a constructor. Every class has at least one constructor method. The pur-
pose of a constructor is to prepare a new object for use. The newoperator creates an empty
object of the given class and then calls the constructor, which can fill in fields of the object
or take any other steps needed to make the object usable. For example, the preceding code
first creates an object of the class InputStreamReaderthat is prepared to use System.inas its
input source. The new object is then assigned to the variable inStream. Constructors are called
only via the newoperator; we cannot write them as normal method calls.

Free download pdf