java - 在 Java 中降低层次结构和平等

标签 java casting

我有以下代码

@Override
public boolean equals(Object o) {
    if (!(o instanceof ColorPoint))
        return false;
    return super.equals(o) && ((ColorPoint) o).color == color;
}

我有以下内容

Point p = new Point(1, 2);
ColorPoint cp = new ColorPoint(1, 2, Color.RED);

ColorPoint 继承Point。问题是当我执行 p.equals(cp) 时,为什么它返回 true?我的意思是在最后一次返回时它调用了 super.equal 但在那个转换中发生了什么?它在使用 ColorPoint

进行转换时返回的内容
@Override public boolean equals(Object o) {
if (!(o instanceof Point))
return false;
Point p = (Point)o;
return p.x == x && p.y == y;
}

这是 Point 类中的 equal

最佳答案

您正在使用 Pointequals 方法,而不是 ColorPoint 的方法。

更改为 cp.equals(p),您将得到 false

请注意,您不应以可能使其不对称的方式实现 equals。始终检查类是否匹配,是否要扩展类:

// in Point class
@Override
public boolean equals(Object other) {
    if (other == null || getClass() != other.getClass()) {
         return false;
    }
    Point p = (Point) other;
    return p.x == x && p.y == y;
}

关于java - 在 Java 中降低层次结构和平等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38740947/

相关文章:

在 C 中将 const void * 转换为 const char *

c# - 为什么 "as T"会出错,但使用 (T) 进行转换不会出错?

java - 将内部类转换为父类(super class)

java - 关于Java中声明为final的变量的一些澄清?

java - 为任何目标部署 Java 应用程序

java - 如何学习用 Java 编写操作系统程序?

c# - 在 linq 查询中转换泛型类型

java - Spring Boot 应用程序无法在 AWS 上运行

Java 将映射序列化到文件

c - "(int)"中的 "sizeof (int)"是类型转换运算符还是某些特殊情况参数? [C]