从java ... Object类重写equals方法

Nic*_*Dry 1 java inheritance overriding overloading

我一直试图弄清楚这个问题背后的基本原理,我一直在努力去理解为什么结果是这样的.我将解释我理解的一切,我希望有人能够填补我的空白.

想象一下你有一堂课:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

现在我们创建以下对象:

Object o = new Object()

Point p = new Point(3,4)

Object op = new Point(3,4)
Run Code Online (Sandbox Code Playgroud)

如果我们打电话:

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

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

p.equals(op) // this calls method 1
Run Code Online (Sandbox Code Playgroud)

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

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

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

op.equals(p) // this calls method 1
Run Code Online (Sandbox Code Playgroud)

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

如果有人能向我解释这将是伟大的!

Era*_*ran 5

op是类型的变量,Object没有签名的方法public boolean equals(Point p).因此,equals通过调用op.equals()(不管参数类型)可以执行的唯一方法是签名boolean equals (Object o).您的Point类会覆盖boolean equals (Object o),因此在后3种情况中都会调用方法1.