0
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".

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.

P.S. I am total beginner in java.

Ana Matijanovic
  • 277
  • 3
  • 13
  • as a side note specifying an enum constructor as `private` is redundant. – Ousmane D. May 19 '17 at 17:19
  • Possible duplicate of [How can I declare enums using java](http://stackoverflow.com/questions/7007137/how-can-i-declare-enums-using-java) – Yahya May 19 '17 at 17:20
  • One cannot write a default constructor. The default constructor is the one provided by the compiler for a class that has no constructor written. – Lew Bloch May 19 '17 at 18:24

4 Answers4

3

The error is coming from declaration of enum members: since the constructor takes String label, you need to supply the string to pass to that constructor:

FOOD("food"), BEVERAGE("bev"), DEFAULT("[default]");
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

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.

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
0

Enum constructor can be called while declaring the Enum members itself.

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

        private final String label;

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

        public String getLabel()
        {
            return label;
        }
    }
Praveen E
  • 926
  • 8
  • 14
0
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;
    }
}
gati sahu
  • 2,576
  • 2
  • 10
  • 16