2011-09-01 124 views
1

我需要創建一個名爲EOHoverFrog的HoverFrog的子類。 EhooverFrog的實例不同於HoverFrog的實例,因爲如果EhooverFrog的兩個實例的位置和高度相同,無論其顏色如何,均認爲這兩個實例相同。實例方法equals()

爲此,我需要爲EOHoverFrog編寫一個實例方法equals(),該方法將覆蓋從Object繼承的equals()方法。該方法應該接受任何類的參數。如果參數的類與接收方的類不同,則該方法應簡單地返回false,否則應測試接收方和參數的相等性。

public boolean equals(Object obj) 
{ 
    Frog.getClass().getHeight(); 
    HeightOfFrog height = (HeightOfFrog) obj; 
    return (this.getPosition() == frog.getPosition()); 
    } 

請你能告訴我,我到底對不對?

+0

考慮到這個代碼甚至不會編譯,我要去......不。 –

回答

4
public boolean equals(Object obj) { 
    // my first (incorrect) attempt, read Carlos Heuberger's comment below 
    // if (!(obj instanceof EOHoverFrog)) 
    // return false; 
    if (obj == null) 
     return false; 
    if (getClass() != obj.getClass()) 
     return false; 
    // now we know obj is EOHoverFrog and non-null 
    // here check the equality for the position and height and return 
    // false if you have any differences, otherwise return true 
} 
+1

注意:'instanceof'不檢查'obj'類是否是EHoverFrog!對於EHoverFrog的任何子類,它也會返回true,但問題要求「參數的類與接收者的類不一樣」 –

1

這似乎不正確。

public boolean equals(Object obj) 
{ 
    Frog.getClass().getHeight(); // you arent assigning this to anything, and class probably 
           // doesn't have a getHeightMethod() 

    HeightOfFrog height = (HeightOfFrog) obj; // obj should be an EOHoverFrog; you should 
              // return false above this if obj is null or the 
              // wrong class 

    return (this.getPosition() == frog.getPosition()); // what is frog? It is not defined 
                 // in your example 

    // you are not comparing heights anywhere. 
} 

實現的equals方法的一個好方法是:

1)確保傳遞的其他對象,obj你的情況,是不是零和正確的類(或類)。在你的情況下,EOHoverFrogHoverFrog實例可以相等嗎?

2)做你的比較,像

//假設兩個高度和位置是在基CALSS

var isHeightEqual = this.getHeight() == ((HoverFrog)obj).getHeight(); 
var isPositionEqual = this.getPosition() == ((HoverFrog)obj).getPosition(); 

3)現在,你是在適當的位置,以檢查平等

return isHeightEqual && isPositionEqual; 
0

首先,閱讀this以瞭解每個equals()方法必須如何表現。其次,如果您重寫equals()方法,那麼在方法之前添加@Override註釋是個好習慣。

要學習示例,您可以學習很多equals()實現here