stackoverflow
stackoverflow

Reputation: 19444

Enum how to return enum's string content inside enum object

Example

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

    String contents;

    STUFF(String x)
    {
       contents = x;
    }

    public String getContents()
    {
        return ??
    }

}

Desired result:

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

Upvotes: 0

Views: 133

Answers (2)

Rohit Jain
Rohit Jain

Reputation: 213263

The assignment in the constructor is wrong.

x = contents;

should be: -

contents = x;

And the return value in getContents() should be: -

public String getContents()
{
    return contents;
}

Upvotes: 3

Freiheit
Freiheit

Reputation: 8767

You should review the planets example at: 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;
    }
 }

Upvotes: 4

Related Questions