我正在尝试创建一个具有不同类型参数的枚举。例如:
enum test {
foo(true, 5), //true is a boolean, 5 is an integer
bar(20, 50), //both arguments are integers
//........
}
当我编写枚举构造函数时,它只能适合两个变量之一的描述。它可以是:
enum test {
foo(true, 5), //true is a boolean, 5 is an integer
bar(20, 50); //both arguments are integers
private boolean bool;
private int i;
private test(boolean bool, int i) {
this.bool = bool;
this.i = i;
}
}
或者构造函数可以是:
private test(int i, int i1) {
this.i = i;
this.i1 = i1;
}
有什么办法可以拥有多个枚举变量,每个变量都有不同的参数(不同类型)
最佳答案
当然,您可以重载构造函数,即 有多个同名但签名不同的构造函数。 像往常一样,在使用重载时,请确保明智地使用它,如 this article 中所述。 .
enum MyEnum {
foo(true, 5),
bar(20, 50);
private boolean bool;
private int num1;
private int num2;
MyEnum(boolean bool, int num) {
this.bool = bool;
this.num1 = num;
}
MyEnum(int num1, int num2) {
this.num1 = num1;
this.num2 = num2;
}
}
关于java - 不同的枚举参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44871130/