【发布时间】:2016-10-08 15:21:02
【问题描述】:
我一直在试图找出这个问题背后的基本原理,并且一直在努力弄清楚为什么结果会是这样。我将解释我所理解的一切,我希望有人能够为我填补空白。
假设你有一堂课:
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 的方法签名不应该保证调用去那里吗?
如果有人可以向我解释,那就太好了!
【问题讨论】:
-
你不能覆盖
Object.equals(Object)的签名。
标签: java inheritance overloading overriding