【问题标题】:Overriding an equals method from the java...Object class覆盖 java...Object 类中的 equals 方法
【发布时间】: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


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    鉴于此

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

    因为opObject

    op.equals(p)
    

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

    【讨论】:

      猜你喜欢
      • 2016-07-12
      • 1970-01-01
      • 2020-01-30
      • 1970-01-01
      • 2020-06-09
      • 1970-01-01
      • 2013-08-20
      • 2014-05-27
      • 2010-09-16
      相关资源
      最近更新 更多