覆盖 java...Object class 中的 equals 方法

Overriding an equals method from the java...Object class

我一直在试图找出这个问题背后的基本原理,并且我一直在努力了解为什么结果是这样。我会解释我所理解的一切,我希望有人能够为我填补空白。

假设你有一个 class:

public class Point {
    public boolean equals(Object o) {
        if (o == null || (!(o instanceof Point)) { // Let's call this method 1
            return false;
        }
        Point other = (Point) o;
        return x == other.x && y == other.y;
    }

    public boolean equals(Point p) { // Let's call this method 2
        if (p == null) {
            return false;
        }
        return x == p.x && y == p.y;
    }
}

现在我们创建以下对象:

Object o = new Object()

Point p = new Point(3,4)

Object op = new Point(3,4)

如果我们调用:

p.equals(o) // this calls method 1

p.equals(p) // this calls method 2

p.equals(op) // this calls method 1

然而,这是我感到困惑的地方。

op.equals(o) // this calls method 1

op.equals(op) // this calls method 1

op.equals(p) // this calls method 1

为什么最后一个调用方法1?方法 2 的方法签名不应该保证调用去那里吗?

如果有人能给我解释一下就好了!

op 是类型 Object 的变量,它没有具有签名 public boolean equals(Point p) 的方法。因此,唯一可以通过调用 op.equals()(无论参数类型如何)执行的 equals 方法具有签名 boolean equals (Object o)。您的 Point class 覆盖了 boolean equals (Object o),因此在后三种情况下都会调用您的方法 1。

鉴于

Point p = new Point(3,4)
Object op = new Point(3,4)

并且由于 opObject

op.equals(p)

将调用 equals(Object o) 方法,因为这是 Object 唯一的 equals 方法。