方法對於下面的代碼:重寫/隱藏Object類的equals()在Java中
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方法應該有 「對象」類的對象作爲參數。我得到的上述行爲的解釋是這裏的equals方法隱藏(而不是覆蓋)Object類的equals()方法。
我不明白爲什麼它藏起來而不是壓倒一切!在重寫equals方法時,我們不能使用子類的對象作爲equals方法的參數嗎?
你didn't覆蓋'equals',因爲它具有簽名'無效的equals(對象)'。嘗試在'equals'實現之前添加'@ Override',你會遇到一個編譯錯誤 – SomeJavaGuy
@Kevin Esche,我想你的意思是說'boolean equals(Object)' –