2013-12-16 179 views
-1

我正在嘗試用Java編寫一個Player類,該類有兩個子類:HumanPlayerComputerPlayer。我想允許用戶選擇與哪個玩家對戰,並且一旦選擇 - 創建相關對象並進行遊戲。處理對象的範圍

由於對象是在if語句中創建的,因此編譯器不允許我在if範圍之外執行任何操作。在其它情況下,我將創建類範圍內的對象,但在這種情況下我不能提前知道哪些對象來創建(人/計算機)

這裏是爲了說明某些代碼:

public class Player { 
    private String name; 

    public String getName(){ 
     return name; 
    } 
} 

public class HumanPlayer extends Player { 
    public void play(){ 
     System.out.println("Human playing"); 
    } 
} 

public class ComputerPlayer extends Player { 
    public void play(){ 
     System.out.println("Computer playing"); 
    } 
} 

import java.util.Scanner; 
public class PlayerDriver { 
    public static void main(String[] args) { 
     Scanner in = new Scanner(System.in); 
     System.out.println("Please type 1 for human, 2 for computer"); 
     int selection = in.nextInt(); 
     if (selection==1){ 
      HumanPlayer player = new HumanPlayer(); 
     } else if (selection==2){ 
      ComputerPlayer player = new ComputerPlayer(); 
     } else { 
      throw new IllegalArgumentException("invalid answer"); 
     } 
     Player.play(); //can't do that 
    } 
} 

回答

3

線束的

Player player = null; // player should never be null as you would have thrown an exception, but for the sake of completeness 
if (selection == 1){ 
    player = new HumanPlayer(); 
} else if (selection == 2){ 
    player = new ComputerPlayer(); 
} else { 
    throw new IllegalArgumentException("invalid answer"); 
} 
player.play(); 

假設Player類的功率具有play()方法。我看到它沒有。將您的課程Player更改爲覆蓋子類型中可覆蓋的play()方法。

+0

完美!感謝您的快速回復 – user2314782