I was looking at the core Java book and the equality test part confused me a bit
&&
otherObject
to Employee when it already know if it's of the same class?class Employee
{
...
public boolean equals(Object otherObject)
{
// a quick test to see if the objects are identical
if (this == otherObject) return true;
// must return false if the explicit parameter is null
if (otherObject == null) return false;
// if the classes don't match, they can't be equal
if (getClass() != otherObject.getClass())
return false;
// now we know otherObject is a non-null Employee
Employee other = (Employee) otherObject;
// test whether the fields have identical values
return name.equals(other.name)
&& salary == other.salary
&& hireDay.equals(other.hireDay);
}
}
It's a logical short-circuiting and operator. It is a shorter (and faster) way to write
if (name.equals(other.name)) {
if (salary == other.salary) {
return hireDay.equals(other.hireDay);
}
}
return false;
(note that the original does not involve branches). As for why it needs a cast for otherObject
to Employee
; it is precisely because it does not know that otherObject
is an Employee
- in fact, you have
public boolean equals(Object otherObject)
which means otherObject
is an Object
(as required by Object.equals(Object)
). You need a cast to tell the compiler that at runtime otherObject
is an Employee
(or throw a class cast exception).
If you expected the compiler to "know" that after
// if the classes don't match, they can't be equal
if (getClass() != otherObject.getClass())
return false;
It's safe to infer otherObject
is an Employee
, I'm sorry to inform you Java does not make any such inference (currently). Compilers aren't sentient (despite seeming like it sometimes).