Equals重写为啥要强制转换同类型

为啥要判断o值与Person类是否一致,不理解
为啥要进行类型强转也不理解
这个方法不就是在相同的地址值里面判断其内容是否一致么

求解

这个可以这么理解,在java语言中,它是支持自动转型的,但只能向上转,因为向上转型一定是安全的。而向下转隐含一定的风险(可能会导致类型转换异常),同时也是为了在比较的时候更加精确的指导两者的类型,因此需要在代码中进行类型判断。

@Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Person other = (Person) obj;
        if (age == null) {
            if (other.age != null)
                return false;
        } else if (!age.equals(other.age))
            return false;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        return true;
    }