2015-10-15 74 views
0

方法對於下面的代碼:重寫/隱藏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方法的參數嗎?

+1

你didn't覆蓋'equals',因爲它具有簽名'無效的equals(對象)'。嘗試在'equals'實現之前添加'@ Override',你會遇到一個編譯錯誤 – SomeJavaGuy

+0

@Kevin Esche,我想你的意思是說'boolean equals(Object)' –

回答

4

它既不隱藏也不壓倒。您的equals方法重載Objectequals方法(重載是適用於具有相同名稱和不同簽名的同一類層次結構中的多個方法的術語)。覆蓋要求重寫方法具有與其覆蓋的方法相同的簽名。

p1.equals(p3)執行Object的等於,因爲您在靜態類型爲Object(在Object p1 = ...中聲明)的實例上執行它。

+0

謝謝@Eran的答案。事實上,它的超載,而不是壓倒一切! –

0

正如@Eran所說,你超載。

這裏是覆蓋它的方式:

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