2016-10-03 4 views
-7
 while (Board[randRow][randColumn] instanceof Wumpus || Board[randRow][randColumn] instanceof Gold 
       || Board[randRow][randColumn] instanceof Pit) 

어떻게 instanceof를 다형성으로 대체합니까?instanceof 키워드를 다형성으로 대체하는 방법은 무엇입니까?

+2

당신이 무엇을하고 싶은가에 따라 다릅니다. 공통 baseclass에 정의 된 메소드를 호출 할 수 있습니다. 'board [randRow] [randColumn] .foo()', 여기서'foo()'는 일반적인 인터페이스 나 추상 수퍼 클래스에서 추상이고 모든 서브 클래스에서 구현됩니다. – Andy

+0

구체적인 유형을 확인하는 데 관심이 있다면이 검사를 별도의 메소드로 추가하고 각 하위 클래스에서이를 대체하십시오. 이러한 검사는 비즈니스 논리의 일부이기 때문에 – maks

답변

2

Wumpus, GoldPit의 공통점은 무엇입니까? 봇/몬스터가이 유형의 셀에 흥미가 있다고 가정 해 보겠습니다.

그래서 인터페이스 정의 :

public interface Cell{ 
    boolean isInterestedForMonster(); 
} 

을 그리고 Wumpus, GoldPit을 위해 그것을 구현 : 사용

public class Gold implements Cell{ 
    @Override public boolean isInterestedForMonster(){ 
     return true; 
    } 
} 

:

Cell cell = Board[randRow][randColumn]; 
while(cell.isInterestedForMonster()){ 
    //Do something 
} 

이것은 당신이 instanceof를 '대체 할 수있는 방법입니다 '다형성이있는 경우

관련 문제