Java Reference
In-Depth Information
return false;
}
}
You might think that our
instanceof
test would allow us to remove the type cast
below it. After all, the
instanceof
test ensures that the comparison occurs only
when
o
refers to a
Point
object. However, the type cast cannot be removed because
the compiler doesn't allow the code to compile without it.
A nice side benefit of the
instanceof
operator is that it produces a
false
result
when
o
is
null
. Thus, if the client code contains an expression such as
p1.equals(null)
, it will correctly return
false
rather than throwing a
NullPointerException
.
Many classes implement an
equals
method like ours, so much of the preceding
equals
code can be reused as boilerplate code. The following is a template for a
well-formed
equals
method. The
instanceof
test and type cast are likely the first
two things you'll want to do in any
equals
method that you write:
public boolean equals(Object o) {
if (o instanceof <type>) {
<type> <name> = (<type>) o;
<compare the data and return the result.>
} else {
return false;
}
}
One of the most powerful benefits of inheritance is that it allows client code to treat
different kinds of objects in the same way. For example, with the employee class
hierarchy described earlier, it's possible for client code to create an array or other
data structure that contains both lawyers and legal secretaries, and then perform oper-
ations on each element of that array. The client code will behave differently depend-
ing on the type of object that is used, because each subclass overrides and changes
some of the behavior from the superclass. This ability for the same code to be used
with several different types of objects is called
polymorphism.
Polymorphism
The ability for the same code to be used with several different types of
objects and for the code to behave differently depending on the actual type
of object used.
Polymorphism is made possible by the fact that the type of a reference variable
(one that refers to an object) does not have to exactly match the type of the object it
Search WWH ::
Custom Search