Java Reference
In-Depth Information
Figure 4
Comparing Object References
191
192
You can use the
equals
method to test whether two rectangles have the same
contents, that is, whether they have the same upper-left corner and the same width
and height. For example, the test
The
==
operator tests whether two object references are identical. To compare
the contents of objects, you need to use the equals method.
box1.equals(box3)
is true.
However, you must be careful when using the
equals
method. It works correctly
only if the implementors of the class have defined it. The
Rectangle
class has an
equals
method that is suitable for comparing rectangles.
For your own classes, you need to supply an appropriate
equals
method. You will
learn how to do that in
Chapter 10
. Until that point, you should not use the
equals
method to compare objects of your own classes.