7

enum has valueOf(string) method to get enum constant and the same type of method present in java.lang.Enum class having name valueOf(enumClassName, string) I found both are giving same output. Then what are other differences. If no difference then why JSL added Enum.valueOf()?

enum Season {
    WINTER,SUMMER
}

class Test {
    public static void main(String[] args) {
        String season = "WINTER";

        //switch (Season.valueOf(colObject))  // following line achieves same thing
        switch (Enum.valueOf(Season.class, season)) // any other difference between both approach
        {
            case WINTER: {
                System.out.println("Got it in switch case= VENDOR");
                break;
            }
            default:
                System.out.println("Fell thru.");
                break;
            }
    }
}
AmitG
  • 10,365
  • 5
  • 31
  • 52
  • This discussion is useful: http://stackoverflow.com/questions/1163076/how-is-values-implemented-for-java-6-enums – Harry Joy Apr 04 '13 at 10:41

3 Answers3

8

The reason the Enum.valueof() method is included is that it works with any enum. By contrast, the enum valueof method for a specific method only works for that specific enum ... since enum classes cannot be used polymorphically.

Obviously the Enum.valueOf(...) method is only really useful if you are implementing code that needs to work for multiple enum types ... and generics don't cut it.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
2

Enum.valueOf(Class<T>, String) is used to implement the valueOf(String) method generated into each specific enum class.

user207421
  • 305,947
  • 44
  • 307
  • 483
1

The method inside Enum is generic and can be used with any enum and the method inside enum is specific to that enum only.

eatSleepCode
  • 4,427
  • 7
  • 44
  • 93
  • why does Enum have .isdefined, but enum does not (i konw enum allows the setting of enumerations) what is Enum?? – Lee Hopkins Jul 30 '19 at 13:23