java - 使用 Switch 语句创建对象 : Cannot make a static reference to the non-static method?

标签 java enums static switch-statement non-static

我试图根据 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/

相关文章:

java - 如何将字符串数据从sqlite for android存储到整数数组中

java - 如何使用 Amazon Cognito 保护我们自己的网络服务?

快速枚举数据

design-patterns - 使用字符串与枚举作为工厂方法的参数?

c++ - 静态与成员变量

c++ - 类中静态对象的重要性以及它们与一般对象的区别

java - 如何正确修补 JAR 文件中的 Java 类?

java - org.hibernate.HibernateException : Unable to instantiate default tuplizer [org. hibernate.tuple.entity.PojoEntityTuplizer]

c++ - Qt 的元系统真的那么乏味吗?

java - 有一个不使用实例变量的非静态方法有意义吗?