1

I want to refactor my enums in the following way: I have enums with method for getting its String value:

public enum Type {
    TYPE_1("Type 1"),
    TYPE_2("Type 2");

    private String value;
    Type(String value) {
        this.name = name;
    }

    public String getValue() {
        return value;
    }
}

I want to get its value simply by toString() method call. According to java.lang.Enum code toString is defined as

public String toString() {
    return this.name;
}

So I guessed all I needed was to redefine name variable in my class:

public enum Type {
    TYPE_1("Type 1"),
    TYPE_2("Type 2");

    private String name;
    Type(String name) {
        this.name = name;
    }
}

But according to debugger there are 2 name variables: in my Type class and in Enum superclass, so toString() returns Enum.name

My question is can I return Type.name in Enum.toString() value without redefining it in subclass?

3
  • 1
    Just override toString and return value (which you have to properly initialize in your constructor in that first snippet). Commented Jun 25, 2019 at 13:54
  • @SotiriosDelimanolis yes, I know it would work, but I want to know if I can use Enum.toString() method for it Commented Jun 25, 2019 at 13:55
  • Everything related with Enum.name is private or final. So you can override it. The way to go is explained above, overriding toString() in your class. Commented Jun 25, 2019 at 13:58

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.