我有以下代码
@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
最佳答案
您正在使用 Point
的 equals
方法,而不是 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/