如何将类的对象分配给值

时间:2018-05-26 17:43:26

标签: java object

这是我想要做的;用户将输入整数1或2.根据数字,它将从类中调用指定的对象。示例如下;

Hero spiderman = new Hero();

Villain venom = new Villain();

int chosen;

Scanner sc = new Scanner(System.in);

System.out.println("Pick one character by number either 1 or 2");

int input = sc.nextInt();

    switch (input) {

    case 1:
        chosen = spiderman;
        System.out.println("You picked Spiderman");
    case 2:
        chosen = venom;
        System.out.println("You picked Venom");
    }

    chosen.fight();
    chosen.block();

我知道'选择'不是对象的正确类型,但我怎么能这样做? 我不一定这样做,但我需要能够根据输入用户putin来调用对象。

非常感谢你。

2 个答案:

答案 0 :(得分:1)

HeroVillainObjects,因此您无法将其分配给int。 我会创建一个类(可能是抽象的)Character,它将由上面提到的两个类扩展。我看到你的两个类都有方法fight()block(),所以通过多态,你可以Character character = new Spiderman();Character character = new Villain();,然后调用character.fight();character.block();

Character character;
int chosen;
Scanner sc = new Scanner(System.in);
System.out.println("Pick one character by number either 1 or 2");
int input = sc.nextInt();

switch (input) {

    case 1:
        character = new Spiderman();
        System.out.println("You picked Spiderman");
    case 2:
        character = new Venom();
        System.out.println("You picked Venom");
    }

character.fight();
character.block();

并且不要忘记

public class Hero extends Character
public class Villain extends Character

答案 1 :(得分:0)

您为选择提供的数据类型为int。您可以做的是为 Hero Villain 类创建父类,并从父类扩展这两个类。对于选择的数据类型,您可以将父类名称作为数据类型。如果我错了,请纠正我!