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
相关产品推荐
相关产品推荐

