我试图根据 type
创建一个对象使用 switch 语句。但是我在 main 方法中的方法上收到此错误:
Cannot make a static reference to the non-static method CreateCoffee(CoffeeFactory.Type) from the type CoffeeFactory
public Coffee CreateCoffee(Type t ) {
ingred = null;
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.CHOCOLATE);
return new Coffee(ingred, t);
default: return null;
}
}
public static void main(String[] args) {
CreateCoffee(Type.MOCHA);
}
我做错了什么,是return new Coffee()
吗?每个 switch case 中的语句?
最佳答案
您需要将 CreateCoffee
方法设置为静态,因为它是直接从静态的 main
方法引用的。
关于java - 使用 Switch 语句创建对象 : Cannot make a static reference to the non-static method?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49607562/