在学习枚举字符串之前,请确保了解 Java 枚举。
在 Java 中,我们可以使用toString()方法或name()方法获取枚举常量的字符串表示形式。 例如,
enum Size {
SMALL, MEDIUM, LARGE, EXTRALARGE
}
class Main {
public static void main(String[] args) {
System.out.println("string value of SMALL is " + Size.SMALL.toString());
System.out.println("string value of MEDIUM is " + Size.MEDIUM.name());
}
} 输出
string value of SMALL is SMALL
string value of MEDIUM is MEDIUM 在上面的示例中,我们已经看到枚举常量的默认字符串表示形式是相同常量的名称。
我们可以通过覆盖toString()方法来更改枚举常量的默认字符串表示形式。 例如,
enum Size {
SMALL {
// overriding toString() for SMALL
public String toString() {
return "The size is small.";
}
},
MEDIUM {
// overriding toString() for MEDIUM
public String toString() {
return "The size is medium.";
}
};
}
class Main {
public static void main(String[] args) {
System.out.println(Size.MEDIUM.toString());
}
} 输出:
The size is medium. 在上面的程序中,我们创建了一个枚举size。 而且,我们已经为枚举常量SMALL和MEDIUM覆盖了toString()方法。
注意:我们无法覆盖name()方法。 这是因为name()方法是final。
要了解更多信息,请访问创建枚举字符串的最佳方法。