2017-01-22 56 views
0

我正在做一項任務,要求我重寫房屋類的equals方法。重寫equals方法時如何指定兩個對象?

的說明如下:

兩個房子都相等時,他們的建築面積相等及其池的狀態是一樣的

到現在爲止,這是我寫的:

@Override 
public boolean equals(Object other) { 
    if (other instanceof House) { 
     House otherHouse = (House) other; 
     return otherHouse.calcBuildingArea() == ??? 
      && otherHouse.mPool == ??? 
    } else { 
     return false; 
    } 
} 

現在我不知道在==標誌後寫什麼。我不知道如何指定調用方法的對象。

+1

您可以使用「this」關鍵字來引用當前對象。 –

+0

你能告訴我你將如何寫這行嗎?我對此有點新...謝謝 –

回答

1

如果您調用方法時未指定對象,則會在當前對象上調用該方法。所以,你可以寫

return otherHouse.calcBuildingArea() == calcBuildingArea() 
     && otherHouse.mPool == mPool; 

,或者如果你想讓它很好的和明確的,明確的,你可以寫

return otherHouse.calcBuildingArea() == this.calcBuildingArea() 
     && otherHouse.mPool == this.mPool; 

還要注意,這個假設mPool是基本類型或enum型。如果它是一個引用類型,如String,你可能需要調用它的equals方法類似

return otherHouse.calcBuildingArea() == calcBuildingArea() 
     && otherHouse.mPool.equals(mPool); 

甚至更​​多空友好

return otherHouse.calcBuildingArea() == calcBuildingArea() 
     && Objects.equals(otherHouse.mPool, mPool); 
+0

哇;驚人的答案 –

0

這個怎麼樣?

return otherHouse.calcBuildingArea() == this.calcBuildingArea() 
     && otherHouse.mPool == this.mPool 
+0

你應該檢查'otherHouse'實際上是'House'。 – ChiefTwoPencils

+0

@ChiefTwoPencils做特定檢查的代碼已經在問題中了。 OP只想知道在問題中用'???'標記寫什麼。這個答案是正確的。 –

+0

@ChiefTwoPencils我只是回答Pshemo關於什麼應該在???的地方的具體問題。這段代碼已經在if塊中了,以確保其他的是House。 – Shiping

相關問題