Java Reference
In-Depth Information
{
return ÐBankAccount[balance=Ð + balance + Ð]Ñ;
}
}
This works better:
BankAccount momsSavings = new BankAccount(5000);
String s = momsSavings.toString();
// Sets s to ÐBankAccount[balance=5000]Ñ
P RODUCTIVITY H INT 10.1: Supply toString in All
Classes
If you have a class whose toString() method returns a string that describes
the object state, then you can simply call System.out.println(x)
whenever you need to inspect the current state of an object x . This works
because the println method of the PrintStream class invokes
x.toString() when it needs to print an object, which is extremely helpful if
there is an error in your program and the objects don't behave the way you think
they should. You can simply insert a few print statements and peek inside the
object state during the program run. Some debuggers can even invoke the
toString method on objects that you inspect.
Sure, it is a bit more trouble to write a toString method when you aren't sure
your program ever needs oneȌafter all, it might work correctly on the first try.
Then again, many programs don't work on the first try. As soon as you find out
that yours doesn't, consider adding those toString methods to help you debug
the program.
A DVANCED T OPIC 10.4: Inheritance and the
toString Method
You just saw how to write a toString method: Form a string consisting of the
class name and the names and values of the instance fields. However, if you
want your toString method to be usable by subclasses of your class, you need
to work a bit harder. Instead of hardcoding the class name, you should call the
getClass method to obtain a class object, an object of the Class class that
Search WWH ::




Custom Search