枚举如何在枚举对象中返回枚举的字符串内容

时间:2012-11-29 17:03:28

标签: java enums

实施例

public enum STUFF
{
    THING("Ok"), STUFF("Sweet"), PEOPLE("umm"), CAR("Vrrm");

    String contents;

    STUFF(String x)
    {
       contents = x;
    }

    public String getContents()
    {
        return ??
    }

}

期望的结果:

System.out.print(STUFF.CAR.getContents());
//Vrrm

2 个答案:

答案 0 :(得分:4)

您应该查看行星示例:http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html

public enum STUFF
{
    THING("Ok"), STUFF("Sweet"), PEOPLE("umm"), CAR("Vrrm");

    private final String contents;

    STUFF(String x)
    {
        contents = x;
    }

    public String getContents()
    {
        return contents;
    }
 }

答案 1 :(得分:3)

构造函数中的赋值是错误的。

x = contents;

应该是: -

contents = x;

getContents()中的返回值应为: -

public String getContents()
{
    return contents;
}