-7
while (Board[randRow][randColumn] instanceof Wumpus || Board[randRow][randColumn] instanceof Gold
|| Board[randRow][randColumn] instanceof Pit)
如何用多態性替換instanceof?如何用多態性替換instanceof關鍵字?
while (Board[randRow][randColumn] instanceof Wumpus || Board[randRow][randColumn] instanceof Gold
|| Board[randRow][randColumn] instanceof Pit)
如何用多態性替換instanceof?如何用多態性替換instanceof關鍵字?
什麼是Wumpus
,Gold
和Pit
? 可以說,殭屍/怪物對這種類型的細胞感興趣。
所以定義一個接口:
public interface Cell{
boolean isInterestedForMonster();
}
並執行它爲Wumpus
,Gold
和Pit
:
public class Gold implements Cell{
@Override public boolean isInterestedForMonster(){
return true;
}
}
使用:
Cell cell = Board[randRow][randColumn];
while(cell.isInterestedForMonster()){
//Do something
}
這就是你如何更換「的instanceof '具有多態性
取決於你想用它做什麼。您可以調用在通用基類中定義的方法,例如'Board [randRow] [randColumn] .foo()',其中'foo()'在一個通用接口或抽象超類中是抽象的,並在每個子類中實現。 – Andy
如果您想檢查具體類型,只需將此檢查作爲單獨的方法添加並在每個子類中覆蓋它們即可。因爲這些檢查是您業務邏輯的一部分 – maks