Java 枚举字符串
Java 枚举字符串
在本教程中,我们将学习了解枚举常量的字符串值。我们还将通过示例学习覆盖枚举常量的默认字符串值。
Java 枚举字符串
在了解枚举字符串之前,请务必了解 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 .我们已经覆盖了 toString()
枚举常量SMALL
的方法 和 MEDIUM
.
注意: 我们不能覆盖 name()
方法。这是因为 name()
方法是 final
.
要了解更多信息,请访问创建枚举字符串的最佳方法。
java