Java Reference
In-Depth Information
The default definition of the method
toString
creates a string that is the name of the
object's
class
, followed by the hash code of the object. For example, in the preceding
statement,
Clock
is the name of the object
myClock
's
class
and the hash code for the
object referenced by
myClock
is
@11b86e7
.
The method
toString
is a
public
value-returning method. It does not take any parameters
and returns the address of a
String
object. The heading of the method
toString
is:
public
String toString()
You can override the default definition of the method
toString
to convert an object to a
desired string. Suppose that for the objects of the
class
Clock
you want the method
toString
to create the string
hh:mm:ss
—the string consists of the object's hour, minutes,
seconds, and the colons as shown. The string created by the method
toString
is the same
as the string output by the method
printTime
of the
class
Clock
. This is easily
accomplished by providing the following definition of the method
toString
:
public
String toString()
{
String str = "";
if
(hr < 10)
str = "0";
str = str + hr + ":";
8
if
(min < 10)
str = str + "0" ;
str = str + min + ":";
if
(sec < 10)
str = str + "0";
str = str + sec;
return
str;
}
In the preceding code,
str
is a
String
variable used to create the required string.
The preceding definition of the method
toString
must be included in the
class
Clock
. In fact, after including the method
toString
in the
class
Clock
, we can
remove the method
printTime
. If the values of the instance variables
hr
,
min
, and
sec
of
myClock
are
8
,
25
, and
56
, respectively, then the output of the statement:
System.out.println(myClock)
is:
08:25:56
You can see that the method
toString
is useful for outputting the values of the instance
variables. Note that the method
toString
only returns the (formatted) string; the methods
print
,
println
,or
printf
output the string.
Search WWH ::
Custom Search