Java Enum toString()方法与示例

枚举类toString()方法

  • toString()方法在java.lang包中可用。

  • toString()方法用于检索此枚举常量的名称,该常量在其枚举声明中声明。

  • toString()方法name()Enum类的方法相似,但toString()大多数由程序员使用,与name()Enum类的方法相比,它更难。

  • toString()方法是一种非静态方法,只能通过类对象访问,如果尝试使用类名称访问该方法,则会收到错误消息。

  • 将对象转换为字符串时,toString()方法不会引发异常。

语法:

    public String toString();

参数:

  • 它不接受任何参数。

返回值:

此方法的返回类型为String,它表示此枚举常量的名称。

示例

//Java程序演示示例 
//toString()枚举的String方法的说明 

enum Month {
    JAN,
    FEB,
    MAR,
    APR,
    MAY;
}

public class ToString {
    public static void main(String args[]) {

        Month m1 = Month.JAN;
        Month m2 = Month.FEB;
        Month m3 = Month.MAR;
        Month m4 = Month.APR;
        Month m5 = Month.MAY;

        System.out.println("Display String Representation: ");

        //通过使用toString()方法是返回名称
        //枚举常量,其枚举定义 
        System.out.println("m1.toString() " + " " + m1.toString());
        System.out.println("m2.toString()" + " " + m2.toString());
        System.out.println("m3.toString()" + " " + m3.toString());
        System.out.println("m4.toString()" + " " + m4.toString());
        System.out.println("m5.toString()" + " " + m5.toString());
    }
}

输出结果

Display String Representation: 
m1.toString()  JAN
m2.toString() FEB
m3.toString() MAR
m4.toString() APR
m5.toString() MAY