0

What exactly is the advantage of enums, considering the following 2 "classes"?

Where lies the advantage in the use of the enum class? In my case here, I don't see a reason to use enums.

StringEnums.class:

package enums;

public enum StringEnum {

    HELLO("Hello String :)"),
    BYE("Bye String :(");

    private final String s;

    StringEnum(String s) { this.s = s; }

    public final String getValue() {
        return s;
    }
}

StringNonEnums.class:

package enums;

public class StringNonEnum {
    public static final String HELLO = "Hello String :)";
    public static final String BYE = "Bye String :(";
}
codepleb
  • 10,086
  • 14
  • 69
  • 111
  • 2
    Part of the point is that you can never ever get the wrong String. You are guaranteed at compile time you will always get HELLO or BYE. – Louis Wasserman Sep 15 '15 at 13:26
  • 1
    It's a shame that the referenced duplicate mentions nothing about the fact that the `StringNonEnum` class would actually never be loaded by the compiler as it only contains inline-able constant fields. – Andy Brown Sep 15 '15 at 13:28
  • 1
    That `StringNonEnum` implementation would actually not fit the description in the linked duplicate. As it is implemented it isn't actually equal to an enum. To achieve that you'd have to make the constructor private, the class final and the constants be of type `StringNonEnum`. But enums have several advantages over a manual implemention as already mentioned in that other article: 1) useful methods such as "valueOf" etc. 2) special support in reflection 3) support in switch-statements (you can't do that with custom classes) etc. – Thomas Sep 15 '15 at 13:34
  • @Thomas Yeah I saw the switch-statement part, but those enums didn't contain a "value". I actually do not get what Louis Wasserman meant by "you can never get the wrong String". If I call "StringNonEnum.HELLO" I won't get another String than the one it references as far as I know. I think I don't understand the point he wanted to show me. – codepleb Sep 15 '15 at 14:11
  • @TrudleR I think what he meant was that with enums you'd normally use them as variarables/parameters and thus can only be null or of an enum value. Thus if you call `getValue()` on a parameter of type `StringEnum` you'll always get the string associated to that enum value. If you use your second approach you'd have to pass a string as a parameter and thus you could pass values other than null or one of the strings defined in `StringNonEnum` (which would then be "wrong") - unless you change that as I described above. It's basically a matter of type safety. – Thomas Sep 16 '15 at 07:20

0 Answers0