클래스의 객체를 사용하여 KeyBoardPlayer
클래스의 상태 변수에 어떻게 액세스 할 수 있습니까?다형성에서 수퍼 클래스의 객체를 사용하여 서브 클래스의 변수에 접근 할 수 있습니까?
/**
* An abstract class representing a player in Kala. Extend this class
* to make your own players (e.g. human players entering moves at the keyboard
* or computer players with programmed strategies for making moves).
*/
public abstract class KalaPlayer {
/**
* Method by which a player selects a move.
* @param gs The current game state
* @return A side pit number in the range 1-6
* @throws NoMoveAvailableException if all side pits for the player are empty
* (i.e. the game is over)
*/
public abstract int chooseMove(KalaGameState gs) throws NoMoveAvailableException;
}
public class KeyBoardPlayer extends KalaPlayer {
/**
* Method by which a player selects a move.
* @param gs The current game state
* @return A side pit number in the range 1-6
* @throws NoMoveAvailableException if all side pits for the player are empty
* (i.e. the game is over)
*/
public KalaGameState state;
public KeyBoardPlayer() {
System.out.println("Enter the number of stones to play with: ");
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int key = Integer.parseInt(br.readLine());
state=new KalaGameState(key);
//key=player1.state.turn;
} catch(IOException e) {
System.out.println(e);
}
}
public int chooseMove(KalaGameState gs) throws NoMoveAvailableException{
return 0;
}
}
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class KalaGame {
KalaPlayer player1,player2;
public KalaGame(KeyBoardPlayer Player1,KeyBoardPlayer Player2) {
//super(0);
player1=new KeyBoardPlayer();
player2 = new KeyBoardPlayer();
//player1=Player1;
//player2=Player2;
//player1.state ****how can i access the stae variable from Keyboard CLass using object from KalaPlayer
key=player1.state.turn;
}
public void play() {
System.out.println("Enter the number of stones to play with: ");
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int key = Integer.parseInt(br.readLine());
System.out.println(key);
KalaGameState state=new KalaGameState(key);
printGame();
} catch(IOException e) {
System.out.println(e);
}
}
}
나는 다형성이 어떻게 작용하는지 약간 혼란 스럽다. 나는 수퍼 클래스 KAlaPLayer와 하위 클래스 키보드를 가지고 있으며 keyboardplayer의 각 인스턴스는 KalaGAmeState의 인스턴스를 가져야합니다. 폴리 모피를 수행하는 경우 KalaPlayer player1 = new KeyboardPLayer(); kalaPLayer.state ***** 상태는 keyboardplayer의 생성자에서 호출되는 kalagamestae의 인스턴스입니다. pls 누구든지 도움을 줄 수 있습니다. – fari