在本教程中,我們將學(xué)習(xí)了解枚舉常量的字符串值。我們還將借助示例學(xué)習(xí)重寫枚舉常量的默認(rèn)字符串值。
在學(xué)習(xí)枚舉字符串之前,請確保已經(jīng)了解Java枚舉。
在Java中,我們可以使用toString()或name()方法獲得枚舉常量的字符串表示形式。例如,
enum Size { SMALL, MEDIUM, LARGE, EXTRALARGE } class Main { public static void main(String[] args) { System.out.println("SMALL的字符串值為 " + Size.SMALL.toString()); System.out.println("MEDIUM的字符串值為 " + Size.MEDIUM.name()); } }
輸出結(jié)果
SMALL的字符串值為 SMALL MEDIUM的字符串值為 MEDIUM
在上面的示例中,我們已經(jīng)看到枚舉常量的默認(rèn)字符串表示形式是相同常量的名稱。
我們可以通過重寫toString()方法來更改枚舉常量的默認(rèn)字符串表示形式。例如,
enum Size { SMALL { //重寫toString()為SMALL public String toString() { return "The size is small."; } }, MEDIUM { //重寫toString()為MEDIUM public String toString() { return "The size is medium."; } }; } class Main { public static void main(String[] args) { System.out.println(Size.MEDIUM.toString()); } }
輸出結(jié)果
The size is medium.
在上面的程序中,我們創(chuàng)建了一個(gè)枚舉Size。并且我們已經(jīng)重寫了枚舉常量SMALL和MEDIUM的toString()方法。
注意:我們無法重寫name()方法。這是因?yàn)閚ame()方法是final類型。