【发布时间】:2020-02-15 08:37:40
【问题描述】:
我在看核心 Java 书,相等性测试部分让我有点困惑
- 这个具体的返回行是什么意思,尤其是
&& - 当它已经知道它是否属于同一类时,为什么还需要将
otherObject转换为 Employee?
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);
}
}
【问题讨论】:
-
&&"in" a return 的含义与其他任何可以使用的地方都一样 -
otherObject的类型为Object。它也可以是Cat,而不是Employee。在该方法中,您确保它实际上是Employee(之前的if)。所以现在你想比较他们的字段,比如姓名和薪水等。为此,你必须告诉 Java “嘿,这实际上是一个Employee,相信我”。否则你无法访问它,因为 Java 会试图保护你不访问猫的薪水,这是行不通的。 -
既然要覆盖equals,就必须覆盖hashCode。
-
某些语言(例如 Kotlin 和 Typescript)确实具有控制流类型缩小,这意味着您不需要在类型得到保证的分支中进行转换。但 Java 不这样做。
-
@kaya3 还没有,但是模式匹配很快就会来,可以把这从两步简化为一步。
标签: java casting return logical-operators