有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在Java中重写/隐藏对象类的equals()方法

对于以下代码:

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) 个答案

  1. # 1 楼答案

    它既不是隐藏的,也不是凌驾的。你的equals方法重载了Objectequals方法(重载这个术语适用于同一类层次结构中具有相同名称和不同签名的多个方法)。重写要求重写方法与其重写的方法具有相同的签名

    p1.equals(p3)执行Object的等于,因为您是在静态类型为Object(如Object p1 = ...中声明的)的实例上执行它的

  2. # 2 楼答案

    正如@Eran所说,你超载了

    下面是一种覆盖它的方法:

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