2017-07-02 74 views
1

我想創建一個類型不同的參數的枚舉。例如:變化枚舉參數

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

有什麼辦法,我可以有各自不同的參數(不同型號)

+0

只讓它成爲3個參數('bool,i,i1'),並設置一個你不需要'0'或'false'的參數。 「test」類型的項目不可能有一組不同的變量。 – zapl

+0

重載構造函數 –

回答

0

當然多個枚舉變量,可以過載構造函數,即 有多個具有相同名稱但簽名不同的構造函數。 像往常一樣使用超載時,請務必明智地使用它,如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; 
    } 
    }