简体   繁体   English

构造函数枚举错误

[英]Constructor Enum error

public enum ProductCategory {
  FOOD, BEVERAGE, DEFAULT;

private final String label;

private ProductCategory(String label){
this.label = label;
}

public String getLabel(){
        return label;
}

I want to implement method getLabel() in this enum class, but I am gettin error: "The constructor ProductCategory() is undefined". 我想在此枚举类中实现方法getLabel(),但我却遇到错误:“构造函数ProductCategory()未定义”。

I already have constructor that I need, what else I need to write? 我已经有了所需的构造函数,还需要编写什么? I tried to write default constructor but again I am getting error. 我尝试编写默认构造函数,但再次出现错误。

PS I am total beginner in java. PS我是java的初学者。

错误来自enum成员的声明:由于构造函数采用String label ,因此您需要提供字符串以传递给该构造函数:

FOOD("food"), BEVERAGE("bev"), DEFAULT("[default]");

The only constructor you've currently got requires a string to be passed in - but all the enum values ( FOOD , BEVERAGE , DEFAULT ) don't specify strings, so they can't call the constructor. 您当前拥有的唯一构造函数要求传入一个字符串-但所有枚举值( FOODBEVERAGEDEFAULT均未指定字符串,因此它们无法调用该构造函数。

Two options: 两种选择:

  • Add a parameterless constructor: 添加一个无参数的构造函数:

     private ProductCategory() {} 

    This wouldn't associate labels with your enum values though. 但是,这不会将标签与您的枚举值相关联。

  • Specify the label on each value: 在每个值上指定标签:

     FOOD("Food"), BEVERAGE("Beverage"), DEFAULT("Default"); 

The latter is almost certainly what you want. 后者几乎可以肯定是您想要的。

Enum constructor can be called while declaring the Enum members itself. 可以在声明Enum成员本身时调用Enum构造函数。

public enum ProductCategory
    {
        FOOD("label1"),
        BEVERAGE("label2"),
        DEFAULT("label3");

        private final String label;

        ProductCategory(String label)
        {
            this.label = label;
        }

        public String getLabel()
        {
            return label;
        }
    }
public enum ProductCategory {
    FOOD("FOOD"), BEVERAGE("BEVERAGE"), DEFAULT("DEFAULT");

    private final String label;

    private ProductCategory(String label) {
        this.label = label;
    }

    public String getLabel() {
        return label;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM