Java Reference
In-Depth Information
Continued from previous page
A key idea to understand about
toString
is that it doesn't directly print any-
thing: It simply returns a
String
that the client can use in a
println
statement.
In fact, many well-formed classes of objects do not contain any
println
statements at all. The inclusion of
println
statements in a class binds that class
to a particular style of output. For example, the preceding code prints a
Point
object on its own line, making the class unsuitable for a client that doesn't want
the output to appear exactly this way (say, a client that wants to print many
Point
objects on the same line).
You may wonder why the designers of Java chose to use a
toString
method
rather than, say, a
print
method that would output the object to the console. The rea-
son is that
toString
is more versatile. You can use
toString
to output the object to
a file, display it on a graphical user interface, or even send the text over a network.
Our third version of the
Point
class will include the ability to create
Point
objects at
any initial location. The initial state of objects is specified by writing
constructors
,
which were introduced in Chapter 3. Recall that a constructor is a piece of code that
initializes the state of new objects as they are created
.
A clumsy aspect of our existing client code is that it takes three lines to create and
initialize the state of one
Point
object:
// client needs 3 statements to initialize one Point object
Point p1 = new Point();
p1.x = 7;
p1.y = 2;
In general, when we have constructed objects, we have been able to declare and
initialize them in a single statement. We might expect that we could initialize a
Point
by writing its initial (
x, y
) values in parentheses as we constructed it:
Point p1 = new Point(7, 2); // desired behavior
However, such a statement wouldn't be legal for our
Point
class, because we
haven't written any code specifying how to create a
Point
with an initial (
x, y
) loca-
tion. We can specify how to do this by writing a constructor in our
Point
class. The
Search WWH ::
Custom Search