You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将类对象赋值给变量?Java实现用户输入选择角色调用方法

解决方法:利用多态统一对象类型

嗨,我来帮你搞定这个问题!你遇到的核心问题是Hero和Villain是两个独立的类,没办法直接把它们赋值给同一个变量——这时候多态就是最适合的解决方案,它能让不同类的对象被统一看待,方便后续调用共同的方法。

步骤1:定义共同的行为规范(接口/抽象类)

因为Hero和Villain都有fight()和block()方法,我们可以先创建一个接口来定义这两个方法的规范,让两个类都实现这个接口:

// 定义接口,规定所有角色必须实现的方法
public interface Character {
    void fight();
    void block();
}

步骤2:让Hero和Villain实现接口

修改你的Hero和Villain类,让它们实现Character接口,并实现接口里的方法:

public class Hero implements Character {
    @Override
    public void fight() {
        System.out.println("Spiderman throws a web punch!");
    }

    @Override
    public void block() {
        System.out.println("Spiderman dodges and blocks with his arms!");
    }
}

public class Villain implements Character {
    @Override
    public void fight() {
        System.out.println("Venom attacks with symbiote tendrils!");
    }

    @Override
    public void block() {
        System.out.println("Venom's symbiote forms a protective barrier!");
    }
}

步骤3:修改主程序,用统一类型接收对象

把chosen的类型改成Character(我们定义的接口类型),这样它就能接收Hero或Villain的对象了。同时别忘了给switch加break,避免执行多个分支,还要处理无效输入的情况:

import java.util.Scanner;

public class CharacterSelector {
    public static void main(String[] args) {
        Hero spiderman = new Hero();
        Villain venom = new Villain();
        Scanner sc = new Scanner(System.in);
        
        System.out.println("Pick one character by number either 1 or 2");
        int input = sc.nextInt();
        
        // 用Character类型的变量接收对象
        Character chosen = null;
        switch (input) {
            case 1:
                chosen = spiderman;
                System.out.println("You picked Spiderman");
                break; // 必须加break,防止执行下一个case
            case 2:
                chosen = venom;
                System.out.println("You picked Venom");
                break;
            default:
                System.out.println("Invalid input! Please choose 1 or 2.");
                sc.close();
                return; // 输入无效时直接退出,避免后续空指针异常
        }
        
        // 现在可以安全调用fight()和block()方法了
        chosen.fight();
        chosen.block();
        sc.close();
    }
}

补充说明

  • 如果你更喜欢用抽象类而不是接口,也可以创建一个abstract class Character,把fight()和block()定义为抽象方法,然后让Hero和Villain继承这个抽象类,效果是完全一样的。
  • 一定要处理无效输入的情况,不然用户输入非1/2的数字时,chosen会保持null,调用方法时会抛出空指针异常。

内容的提问来源于stack exchange,提问作者James Kang

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:03:06