简体   繁体   中英

Java Enum Constructor Undefined

Why am i getting an error "Constructor is undefined" is it in my eclipse IDE? is there something wrong with my code?

public enum EnumHSClass {
    PALADIN ("Paladin"),ROUGE("ROUGE");
}

If you expect your enums to have parameters, you need to declare a constructor and fields for those parameters.

public enum EnumHSClass {
    PALADIN ("Paladin"),ROUGE("ROUGE");
    private final String name;
    private EnumHSClass(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

You need to provide a constructor in your enum like:

public enum EnumHSClass {

    PALADIN("Paladin"), ROUGE("ROUGE");

    String value;

    EnumHSClass(String value) {
        this.value = value;
    }
}

Note: The constructor for an enum type must be package-private or private access. It automatically creates the constants that are defined at the beginning of the enum body. You cannot invoke an enum constructor yourself.

Ref : http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html

Enums have constructors too, but only with either private or default visibility:

public enum EnumHSClass {
    PALADIN ("Paladin"),ROUGE("ROUGE");
    private EnumHSClass(String s) {
        // do something with s
    }
}

You may want to declare a field and create a getter for it, and set the field in the constructor.

Also note that the name of the enum instance is available for free via the (implicit) name() method that all enums have - maybe you can use that instead.

Your code should look like this:

public enum EnumHSClass {

    PALADIN ("Paladin"), ROUGE("ROUGE");

    private String name;

    private  EnumHSClass(String name) {
        this.name = name;
    } 
}
public enum Days {
    MONDAY(1), TUESDAY(2);
    int val;
    Days (int val) {
        this.val = val;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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