Java Reference
In-Depth Information
to turn the object into a string. Then both strings are concatenated. In this case, the
result is the string
Ðbox=java.awt.Rectangle[x=5,y=10,width=20,height=30]Ñ
The compiler can invoke the toString method, because it knows that every
object has a toString method: Every class extends the Object class, and that
class defines toString .
As you know, numbers are also converted to strings when they are concatenated
with other strings. For example,
int age = 18;
String s = ÐHarryÓs age is Ñ + age;
// Sets s to ÐHarryÓs age is 18Ñ
In this case, the toString method is not involved. Numbers are not objects, and
there is no toString method for them. There is only a small set of primitive
types, however, and the compiler knows how to convert them to strings.
Let's try the toString method for the BankAccount class:
BankAccount momsSavings = new BankAccount(5000);
String s = momsSavings.toString();
// Sets s to something like ÐBankAccount@d24606bfÑ
That's disappointingȌall that's printed is the name of the class, followed by the
hash code, a seemingly random code. The hash code can be used to tell objects
apartȌdifferent objects are likely to have different hash codes. (See Chapter 16 for
the details.)
We don't care about the hash code. We want to know what is inside the object. But,
of course, the toString method of the Object class does not know what is
inside the BankAccount class. Therefore, we have to override the method and
supply our own version in the BankAccount class. We'll follow the same format
that the toString method of the Rectangle class uses: first print the name of
the class, and then the values of the instance fields inside brackets.
public class BankAccount
{
. . .
public String toString()
466
467
Search WWH ::




Custom Search