Programming and Problem Solving with Java

(やまだぃちぅ) #1
2.1 The Elements of Java Programs | 69

Constructors have a special feature that requires some further explanation. The call to
the constructor method isn’t preceded by an object name or a class name as in the case for
System.out.print, for example. If you stop to consider that the constructor creates an object
beforeit is assigned to a field, you realize that it can’t be associated with a particular object
name. We don’t have to precede the constructor name with the class name because its name
already tells Java to which class it belongs.
The capitalization of a constructor doesn’t follow our usual rule of starting each method
name with a lowercase letter. By convention, all class names in the Java library begin with
an uppercase letter, and the constructor name mustbe spelled exactly the same as the name
of the class that contains it.
The BufferedReaderclass has a constructor that takes an InputStreamReaderobject as an
argument and prepares a BufferedReaderobject that uses the InputStreamReaderobject as its
input source. Thus we can write


BufferedReader in; // A variable of class BufferedReader
in = new BufferedReader(inStream);


We now have an object, assigned to the variable in, which is a BufferedReaderthat takes its
input from inStream, which in turn takes its input from System.in.
We can shorten this process by nesting the constructor calls as follows:


in = new BufferedReader(new InputStreamReader(System.in));


This one statement has the same effect as writing


InputStreamReader inStream; // A variable of class InputStreamReader
inStream = new InputStreamReader(System.in);
in = new BufferedReader(inStream);


It also avoids the need to declare a separate variable to hold the InputStreamReader
object. The inner newoperator still creates the object, but it is not assigned to a vari-
able and, therefore, has no name. Objects that lack a name are said to beanonymous.


readLine The class BufferedReadergives us another useful method, called readLine. Its name
is descriptive of its function: The computer “reads” what we type into it on one line and re-
turns the characters we type as a string. Here is an example of using readLine:


String oneLineOfTyping; // A variable of class String
oneLineOfTyping = in.readLine();


Notice that a call to readLineis quite different from a call to println. We call printlnas a
separate statement:


System.out.println(“A line of text to output.”);


Anonymous object An object
that is instantiated but not as-
signed to an identifier and,
therefore, lacks a name
Free download pdf