Java Reference
In-Depth Information
Suppose you have an instance v of some class and method toString is
defined in the class. To find out what the instance contains, simply type v into the
DrJava Interactions pane; automatically, the value of the call v.toString() will
be printed.
Here is another way in which toString is useful. Execution of
System.out.println(v.toString());
will print the description of instance v in the Java console. As another example,
to assign a description of instance v to String variable s , use the assignment:
s= v.toString();
Implicit calls to toString
In certain situations, given the name v of a class instance, Java will auto-
matically call method toString of the instance. For example, one can give v as
the argument of a println or print statement, and the effect is as if the argument
was v.toString() :
System.out.println(v);
Consider attempting to assign the description of instance v to String s
using this assignment:
s= b; // Syntactically incorrect
Because of Java's typing rules for assignment, this statement is syntactically
incorrect. Instead, write the assignment like this:
Activity 3-7.3
shows how a
call to toString
is evaluated,
step by step.
s= "" + b;
Since one operand of + is a String , the other operand is converted to a String
using its method toString ; then the catenation of "" with the converted value is
assigned to s .
Make the toString description fit the problem
The form of the description produced by function toString should be in
terms of the area with which the class is concerned. For example, consider a class
Point whose instances are points in the xy plane. Then, toString should pro-
duce conventional notation for points, e.g. "(5,3)".
As another example, suppose that a class BowlingFrame contains the results
of one frame of the American game of bowling. Function toString could pro-
duce the notation used for keeping score in that game, e.g. "X" for a strike, "8/"
for a spare on which the first ball knocked down 8 pins, and "81" for a frame in
which the first ball knocked down 8 pins and the second 1 .
Take the time to write function toString so that it produces the description
in the notation of the problem domain. It will make future testing and debugging
easier.
Activity
3-7.4
Search WWH ::




Custom Search