覆盖/隐藏Java中的Object类的equals()方法

时间:2015-10-15 10:23:10

标签: java equals method-overriding

对于以下代码:

public class Point {

    private int xPos, yPos;

    public Point(int x, int y) {
        xPos = x;
        yPos = y;
    }

    // override the equals method to perform
    // "deep" comparison of two Point objects
    public boolean equals(Point other) {
        if (other == null)
            return false;
        // two points are equal only if their x and y positions are equal
        if ((xPos == other.xPos) && (yPos == other.yPos))
            return true;
        else
            return false;
    }

    public static void main(String[] args) {
        Object p1 = new Point(10, 20);
        Object p2 = new Point(50, 100);
        Object p3 = new Point(10, 20);
        System.out.println("p1 equals p2 is " + p1.equals(p2));
        System.out.println("p1 equals p3 is " + p1.equals(p3));
    }
}

输出结果为:

p1 equals p2 is false
p1 equals p3 is false

我知道equals方法应该将“Object”类的对象作为参数。我得到的上述行为的解释是,这里equals方法隐藏(而不是覆盖)equals()方法 对象类。

我不明白为什么它会隐藏而不是压倒一切!在重写equals方法时,我们不能将子类的对象用作equals方法的参数吗?

2 个答案:

答案 0 :(得分:4)

既不是隐藏也不是压倒一切。您的equals方法重载Object的{​​{1}}方法(重载是适用于具有相同名称和不同签名的同一类层次结构中的多个方法的术语)。覆盖要求覆盖方法与其覆盖的方法具有相同的签名。

equals执行p1.equals(p3)的等号,因为您在静态类型为Object的实例上执行它(如Object中所声明的那样)。

答案 1 :(得分:0)

正如@Eran所说,你正在超载。

这是一种覆盖它的方法:

   @Override
    public boolean equals(Object obj) {
        return obj == null ? false : ((xPos == (Point)obj.xPos) && (yPos == (Point)obj.yPos));
    }