Ana Matijanovic
Ana Matijanovic

Reputation: 277

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

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.

Upvotes: 0

Views: 2423

Answers (4)

gati sahu
gati sahu

Reputation: 2626

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;
    }
}

Upvotes: 0

Praveen E
Praveen E

Reputation: 976

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;
        }
    }

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500065

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.

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726489

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]");

Upvotes: 3

Related Questions