Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between Enum and enum

Tags:

java

enums

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;
            }
    }
}
like image 350
AmitG Avatar asked Jan 13 '23 18:01

AmitG


2 Answers

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.

like image 126
Stephen C Avatar answered Jan 17 '23 07:01

Stephen C


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

like image 24
user207421 Avatar answered Jan 17 '23 07:01

user207421