为什么在 return 和铸造中使用 &&?

Why && in return and casting?

我在看核心 Java 书,平等测试部分让我有点困惑

  1. 这个特定的 return 行是什么意思,尤其是 &&
  2. 为什么它需要将 otherObject 转换为 Employee,因为它已经知道它是否属于相同的 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);
    }
}

&& 是逻辑运算符的一种,读作“AND AND”或“Logical AND”。该运算符用于进行“逻辑与”运算,即类似于数字电子学中的与门的功能。

要记住的一件事是,如果第一个条件为假,则不会评估第二个条件,即它具有短路效果。广泛用于测试做出决定的几个条件。

这是一个逻辑短路和运算符。这是一种更短(更快)的写法

if (name.equals(other.name)) {
    if (salary == other.salary) {
        return hireDay.equals(other.hireDay);
    }
}
return false;

(注意原文不涉及分支)。至于为什么需要将 otherObject 转换为 Employee;正是因为它不知道 otherObject 是一个 Employee - 事实上,你有

public boolean equals(Object otherObject)

这意味着 otherObject 是一个 Object(根据 Object.equals(Object) 的要求)。您需要一个强制转换来告诉编译器在运行时 otherObject 一个 Employee(或抛出一个 class 强制转换异常)。

如果您希望编译器 "know" 在

之后
// if the classes don't match, they can't be equal 
if (getClass() != otherObject.getClass())
   return false;

可以安全地推断 otherObject 是一个 Employee,很遗憾地通知您 Java 没有做出任何此类推断(目前)。编译器没有感知力(尽管有时看起来像)。