Java 简明教程
Java - Enum String
Java enum 是一个特殊结构,用于表示一组预定义的常量 strings,并且在用作应用程序代码中的常量时在代码中提供清晰性。默认情况下,enum string 表示法与其声明相同。考虑以下示例:
enum WEEKDAY { MONDAY, TUESDAY, WEDNESDAY, THRUSDAY, FRIDAY, SATURDAY, SUNDAY }
如果我们使用 enum 直接打印上述枚举的字符串表示,使用 toString() 或使用 name() 方法,它会打印与声明相同的字符串。
System.out.println(WEEKDAY.MONDAY);
System.out.println(WEEKDAY.MONDAY.toString());
System.out.println(WEEKDAY.MONDAY.name());
它会按如下所示打印结果:
MONDAY
MONDAY
MONDAY
Overriding Enum toString() Method
现在,如果我们希望将默认字符串表示法更改为枚举的字符串表示法,我们可以为 enum constructor 的每个值创建重写的 toString() 方法,如下所示:
enum WEEKDAY {
MONDAY{
// overridden toString() method per value
public String toString() {
return "Day 1 of the Week: Monday";
}
};
// or override toString() per enum
// priority will be given to value level toString() method.
public String toString() {
return "Day 1 of the Week: Monday";
}
}
在此情况下,我们重写枚举的默认 toString() 方法,以提供自定义描述。
Example: Overriding toString() Method in Java
在此示例中,我们创建了枚举 WEEKDAY。使用 toString() 方法,我们设置枚举值的自定义描述。
package com.tutorialspoint;
enum WEEKDAY {
// enum value constants
MONDAY, TUESDAY, WEDNESDAY, THRUSDAY, FRIDAY, SATURDAY, SUNDAY;
// override the toString() method for custom description
@Override
public String toString() {
return switch(this) {
case MONDAY: yield "Day 1";
case TUESDAY:yield "Day 2";
case WEDNESDAY:yield "Day 3";
case THRUSDAY:yield "Day 4";
case FRIDAY:yield "Day 5";
case SATURDAY:yield "DAY 6";
case SUNDAY: yield "Day 7";
};
}
}
public class Tester {
public static void main(String[] args) {
// invoke toString() internally
System.out.println(WEEKDAY.MONDAY);
// invoke toString explicitly
System.out.println(WEEKDAY.TUESDAY.toString());
// invoke name() method to get the default name
System.out.println(WEEKDAY.WEDNESDAY.name());
}
}
让我们编译并运行上述程序,这将生成以下结果 −
Day 1
Day 2
WEDNESDAY
Example: Overriding toString() Method Per Value in Java
在此示例中,我们重写了此枚举 WEEKDAY 每个值的 toString() 方法。这种方式,我们也可以自定义字符串表示。
package com.tutorialspoint;
enum WEEKDAY {
// override the toString() method for custom description
MONDAY{
@Override
public String toString() {
return "Day 1";
}
},
TUESDAY{
@Override
public String toString() {
return "Day 2";
}
},
WEDNESDAY{
@Override
public String toString() {
return "Day 3";
}
},
THRUSDAY{
@Override
public String toString() {
return "Day 4";
}
},
FRIDAY{
@Override
public String toString() {
return "Day 5";
}
},
SATURDAY{
@Override
public String toString() {
return "Day 6";
}
},
SUNDAY{
@Override
public String toString() {
return "Day 7";
}
};
}
public class Tester {
public static void main(String[] args) {
// invoke toString() internally
System.out.println(WEEKDAY.MONDAY);
// invoke toString explicitly
System.out.println(WEEKDAY.TUESDAY.toString());
// invoke name() method to get the default name
System.out.println(WEEKDAY.WEDNESDAY.name());
}
}
让我们编译并运行上述程序,这将生成以下结果 −
Day 1
Day 2
WEDNESDAY
enum name() 方法是最终的,不能被重写。当枚举的字符串表示被 toString() 方法重写时,它可用于获取枚举的默认名称。