Java Reference
In-Depth Information
to the object that was referred to by
p2
. This means that a change to
p2
, such as a call
of its
translate
method, would also be reflected in
p3
:
p1
x 3
x 7 y 2
p2
x 3
x 7 y 2
p3
In the case of the preceding
Point
objects, the expression
p1 == p2
would evalu-
ate to false because
p1
and
p2
do not refer to the same object. The object referred to
by
p1
has the same state as
p2
's object, but they have different identities. The expres-
sion
p2 == p3
would evaluate to
true
, though, because
p2
does refer to the same
object as
p3
.
Often, when comparing two objects, we want to know whether the objects have
the same state. To perform such a comparison, we use a special method called
equals
. Every Java object contains an
equals
method that it uses to compare itself
to other objects.
The previous section mentioned that a class without a
toString
method receives
a default version of the method. Similarly, a class without an
equals
method
receives a default version that uses the most conservative definition of equality, con-
sidering two objects to be equal only if they have the same identity. This means that
the default
equals
method behaves identically to the
==
operator. If you want a
method that will behave differently, you must write your own
equals
method to
replace the default behavior.
A proper
equals
method performs a comparison of two objects' states and returns
true
if the states are the same. With the preceding
Point
objects, we'd like the
expressions
p1.equals(p2)
,
p1.equals(p3)
, and
p2.equals(p3)
to evaluate to
true
because the
Point
s all have the same (
x
,
y
) coordinates.
You can imagine a piece of client code that examines two
Point
objects to see
whether they have the same
x
and
y
field values:
if (p1.getX() == p2.getX() && p1.getY() == p2.getY()) {
// the objects have equal state
...
}
But the
equals
functionality should actually be implemented in the
Point
class
itself, not in the client code. Rather than having two
Point
s
p1
and
p2
, the
equals
method considers the first object to be the “implicit parameter” and accepts the sec-
ond object as a parameter. It returns
true
if the two objects are equal.
Search WWH ::
Custom Search