我一直在试图找出这个问题背后的基本原理,并且一直在努力弄清楚为什么会出现这样的结果。我会解释我所理解的一切,我希望有人能够为我填补空白。
假设你有一个类:
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
类覆盖了 boolean equals (Object o)
,因此您的方法 1 在后三种情况下都会被调用。
关于java - 覆盖 java...Object 类中的 equals 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39934067/