Java 枚举构造函数未定义
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24990639/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java Enum Constructor Undefined
提问by Chizbox
Why am i getting an error "Constructor is undefined" is it in my eclipse IDE? is there something wrong with my code?
为什么我在 Eclipse IDE 中收到错误“构造函数未定义”?我的代码有问题吗?
public enum EnumHSClass {
PALADIN ("Paladin"),ROUGE("ROUGE");
}
回答by Shail016
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
回答by guardian
Your code should look like this:
您的代码应如下所示:
public enum EnumHSClass {
PALADIN ("Paladin"), ROUGE("ROUGE");
private String name;
private EnumHSClass(String name) {
this.name = name;
}
}
回答by Bohemian
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()
所有枚举具有的(隐式)方法免费获得 - 也许您可以使用它。
回答by QBrute
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;
}
}
回答by David Prun
public enum Days {
MONDAY(1), TUESDAY(2);
int val;
Days (int val) {
this.val = val;
}
}