Java Reference
In-Depth Information
+ used
with objects
In this case, it is really the plus operator that causes the automatic invocation of
toString()
. So, the following is also legal:
String s = date1 + " equals " + date2;
The preceding is equivalent to
String s = date1.toString() + " equals " + date2.toString();
Recursive Methods
Java does allow
recursive method
definitions. Recursive methods are covered in
Chapter 11 . If you do not know what recursive methods are, do not be concerned
until you reach that chapter. If you want to read about these methods early, you can
read Sections 11.1 and 11.2 of Chapter 11 after you complete Chapter 5 .
recursive
method
The Methods
equals
and
toString
Usually, your class definitions should contain an
equals
method and a
toString
method.
An
equals
method compares the calling object to another object and should return
true
when the two objects are intuitively equal. When comparing objects of a class type, you
normally use the method
equals
not
==
.
The
toString
method should return a string representation of the data in the calling object.
If a class has a
toString
method, you can use an object of the class as an argument to the
methods
System.out.println
and
System.out.print
.
See Display 4.7 for an example of a class with
equals
and
toString
methods.
TIP: Testing Methods
Each method should be tested in a program in which it is the only untested program.
If you test methods this way, then when you find an error, you will know which
method contains the error. A program that does nothing but test a method is called a
driver program
.
If one method contains an invocation of another method in the same class, this
can complicate the testing task. One way to test a method is to first test all the
methods invoked by that method and then test the method itself. This is called
bottom-up testing
.
driver
program
bottom-up
testing
(continued)