Java Reference
In-Depth Information
preceding code produces errors such as the following for each of
o
's fields that we
try to access:
Point.java:36: cannot find symbol
symbol : variable x
location: class java.lang.Object
If we want to treat
o
as a
Point
object, we must cast it from type
Object
to type
Point
. We've already discussed typecasting to convert between primitive types, such
as casting
double
to
int
. Casting between object types has a different meaning. A
cast of an object is a promise to the compiler. The cast is your assurance that the
reference actually refers to a different type and that the compiler can treat it as that
type. In our method, we'll write a statement that casts
o
into a
Point
object so the
compiler will trust that we can access its
x
and
y
fields:
// returns whether the two Points have the same (x, y) values
public boolean equals(Object o) {
Point other = (Point) o;
return x == other.x && y == other.y;
}
Don't forget that if your object has fields that are objects themselves, such as a
string or
Point
as a field, then those fields should be compared for equality using
their
equals
method and not using the
==
operator.
By changing our
equals
method's parameter to type
Object
, we have allowed
objects that are not
Point
s to be passed. However, our method still doesn't behave
properly when clients pass these objects. An expression in client code such as
p.equals(
"
hello
"
)
will produce an exception like the following at runtime:
Exception in thread "main"
java.lang.ClassCastException: java.lang.String
at Point.equals(Point.java:25)
at PointMain.main(PointMain.java:25)
The exception occurs because it is illegal to cast a
String
into a
Point
; these are
not compatible types of objects. To prevent the exception, our
equals
method will
need to examine the type of the parameter and return
false
if it isn't a
Point
. The
following pseudocode shows the pattern that the code should follow:
public boolean equals(Object o) {
if (o is a Point object) {
compare the x and y values.
Search WWH ::
Custom Search