简体   繁体   English

Java Enum构造函数未定义

[英]Java Enum Constructor Undefined

Why am i getting an error "Constructor is undefined" is it in my eclipse IDE? 为什么我收到错误“构造函数未定义”是否在我的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: 你需要在你的枚举中提供一个constructor ,如:

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 参考: 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. 您可能希望声明一个字段并为其创建一个getter,并在构造函数中设置该字段。

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. 另请注意,枚举实例的名称可通过所有枚举所具有的(隐式) name()方法免费获得 - 也许您可以使用它。

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

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

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