Hey, I am a big fan of using Enumerated Types in Java to aid with code readability and restriction of invalid values. However, I have been told there is much more that can be done in Java with enums than just creating a named group of possible values.
Could someone list the basic functionality that Java's enums allow as well as an example or perhaps a location where I could get more information on that functionality?
Thank you much, Black Vegetable
EDIT: As suggested, this question should be asking what differences there are between an enum and a class in Java. I wasn't aware they were that powerful? What ARE the differences then?
Java's enum is basically a full-grown class.
You can:
But you can't:
enums implicitly extend java.lang.Enum already and Java only supports single implementation inheritance)They have:
valueOf and valuesThe differences between an enum and a normal class are primarily the guarantees given to you by the JVM's handling of enums.
Lets say you have an enum class (MyEnum) with values (VALUE1 and VALUE2). You are guaranteed that the constructor for that enum class will only ever be executed twice in your JVM*, when serializing and deserializing VALUE1 and VALUE2 you are guaranteed to get the same objects every time so that way object equality works (whereas it will not be guaranteed with other classes... (for example "Foo" == new String("Foo") could return false).
Additionally every enum class extends Enum<T extends Enum<T>> so you can work with these enum types in a generic fasion as needed (learn to love name() and valueOf()).
*Classloaders are tricky business... yes there's a slight exception here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With