Java Reference
In-Depth Information
The designers of Java felt that it was important for all types of values to work well
with
String
s. You've seen that you can concatenate
String
s with any other type of
value, such as primitive
int
s or other objects. Consider the following code:
int i = 42;
String s = "hello";
Point p = new Point();
System.out.println("i is " + i);
System.out.println("s is " + s);
System.out.println("p is " + p);
Using the
Point
class that we've written so far, the preceding code produces out-
put like the following:
i is 42
s is hello
p is Point@119c082
Notice that printing
p
generated a strange result. We'd rather have it print the
object's state of (0, 0), but Java doesn't know how to do so unless we write a special
method in our
Point
class.
When a Java program is printing an object or concatenating it with a
String
, the
program calls a special method called
toString
on the object to convert it into a
String
. The
toString
method is an instance method that returns a
String
repre-
sentation of the object. A
toString
method accepts no parameters and has a
String
return type:
public String toString() {
<code to produce and return the desired string>;
}
If you don't write a
toString
method in your class, your class will use a default
version that returns the class name followed by an
@
sign and some letters and num-
bers related to the object's address in memory. If you define your own
toString
method, it replaces this default version.
The following code implements a
toString
method for our
Point
objects and
returns a
String
such as
"(0, 0)"
:
// returns a String representation of this point
public String toString() {
return "(" + x + ", " + y + ")";
}
Search WWH ::
Custom Search