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

Java构造器内switch调用super违反语法的解决方案咨询

解决思路

方案1:用静态方法生成super参数

把根据effect获取名称的逻辑抽成静态方法,直接在super调用里使用,保证super是构造器的第一条语句:

package Items;

public class Potion extends Item {
    private int effect;
    private int amount;

    // 静态方法根据effect返回对应药水名称
    private static String getPotionName(int effect) {
        return switch(effect) {
            case 0 -> "Potion of regeneration";
            case 1 -> "Potion of attack power";
            default -> "Unknown Potion"; // 处理未定义的effect值
        };
    }

    public Potion(int effect, int amount) {
        super(getPotionName(effect), "", "Potion");
        this.effect = effect;
        this.amount = amount;
    }
}

方案2:重载构造器

新增一个私有构造器负责调用父类构造,公开的构造器根据effect选择参数调用这个私有构造器:

package Items;

public class Potion extends Item {
    private int effect;
    private int amount;

    // 私有构造器,统一处理父类调用和属性赋值
    private Potion(String name, String desc, String type, int effect, int amount) {
        super(name, desc, type);
        this.effect = effect;
        this.amount = amount;
    }

    public Potion(int effect, int amount) {
        this(
            switch(effect) {
                case 0 -> "Potion of regeneration";
                case 1 -> "Potion of attack power";
                default -> "Unknown Potion";
            },
            "",
            "Potion",
            effect,
            amount
        );
    }
}

方案3:用枚举管理药水类型(更推荐)

把药水类型和对应属性封装成枚举,避免魔法值,代码可读性和维护性更强:

package Items;

public class Potion extends Item {
    private PotionType type;
    private int amount;

    // 枚举定义每种药水的属性
    public enum PotionType {
        REGENERATION("Potion of regeneration", ""),
        ATTACK_POWER("Potion of attack power", "");

        private final String name;
        private final String description;

        PotionType(String name, String description) {
            this.name = name;
            this.description = description;
        }

        public String getName() { return name; }
        public String getDescription() { return description; }
    }

    public Potion(PotionType type, int amount) {
        super(type.getName(), type.getDescription(), "Potion");
        this.type = type;
        this.amount = amount;
    }
}

使用时直接传入PotionType.REGENERATION这类枚举值,不用再传容易出错的int数字。

内容的提问来源于stack exchange,提问作者Mr.Sponge

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 06:30:08