变化枚举参数
问题描述:
我想创建一个类型不同的参数的枚举。例如:变化枚举参数
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;
}
}
只让它成为3个参数('bool,i,i1'),并设置一个你不需要'0'或'false'的参数。 “test”类型的项目不可能有一组不同的变量。 – zapl
重载构造函数 –