对于以下代码:
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 方法的参数吗?
最佳答案
它既不隐藏也不压倒一切。您的 equals
方法重载了 Object
的 equals
方法(重载这个术语适用于同一类层次结构中具有相同名称和名称的多个方法)不同的签名)。重写要求重写方法与其重写的方法具有相同的签名。
p1.equals(p3)
执行 Object
的 equals,因为您在静态类型为 Object
的实例上执行它(如Object p1 = ...
中声明的那样)。
关于java - Java 中重写/隐藏对象类 equals() 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33145978/