处理对象的范围

时间:2013-12-16 00:27:29

标签: java oop

我正在尝试用Java编写一个带有Player类的游戏,该类有2个子类: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
    }
}

1 个答案:

答案 0 :(得分:3)

利用polymorphism

的力量
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()方法,您可以在子类型中覆盖该方法。