使用Switch语句创建对象时遇报错:无法对非静态方法进行静态引用
解决静态引用非静态方法的错误
首先,咱们来拆解你遇到的这个错误:Cannot make a static reference to the non-static method CreateCoffee(CoffeeFactory.Type) from the type CoffeeFactory,本质原因是静态方法(比如main方法)无法直接调用类中的非静态成员方法。
Java里,静态方法属于类本身,不需要创建类的实例就能调用;而非静态方法属于类的实例对象,必须先创建对象才能调用。你的CreateCoffee方法是非静态的,但你在静态的main方法里直接通过CoffeeFactory.CreateCoffee(...)调用,这就违反了这个规则。
下面给你两种可行的解决方案:
方案一:将CreateCoffee改为静态方法
直接在方法声明前加上static修饰符,让它变成类的静态方法,这样main里就能直接调用了:
public static Coffee CreateCoffee(Type t ) { // 注意:这里要先初始化ingred,不然会触发空指针异常! List<Ingredient> ingred = new ArrayList<>(); switch (t) { case LONG_BLACK: ingred.add(Ingredient.ESPRESSO); return new Coffee(ingred, t); case FLAT_WHITE: ingred.add(Ingredient.MILK); return new Coffee(ingred, t); case MOCHA: ingred.add(Ingredient.ESPRESSO); ingred.add(Ingredient.MILK); ingred.add(Ingredient.CHOCOLATE); return new Coffee(ingred, t); // 建议添加default分支处理未知类型,避免遗漏 default: throw new IllegalArgumentException("Unknown coffee type: " + t); } }
之后在main方法里直接调用即可:
public static void main(String[] args) { Coffee myCoffee = CoffeeFactory.CreateCoffee(CoffeeFactory.Type.LONG_BLACK); }
方案二:创建CoffeeFactory的实例,通过实例调用方法
如果不想把方法改成静态的,那就先实例化一个CoffeeFactory对象,再调用它的非静态方法:
public static void main(String[] args) { CoffeeFactory factory = new CoffeeFactory(); Coffee myCoffee = factory.CreateCoffee(CoffeeFactory.Type.FLAT_WHITE); }
⚠️ 额外提醒:你原来的代码里ingred = null;之后直接调用ingred.add(...),这会触发NullPointerException!一定要先初始化ingred为一个具体的集合对象,比如ArrayList<Ingredient>,就像方案一里写的那样。
内容的提问来源于stack exchange,提问作者billy
相关产品推荐
相关产品推荐

