Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Enumerated Types: Functionality

Tags:

java

enums

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?

like image 591
BlackVegetable Avatar asked Feb 23 '26 17:02

BlackVegetable


2 Answers

Java's enum is basically a full-grown class.

You can:

  • Declare methods and fields
  • Implement interfaces

But you can't:

  • Extend classes (because enums implicitly extend java.lang.Enum already and Java only supports single implementation inheritance)
  • Have public constructors

They have:

  • Some compiler-generated methods like valueOf and values
  • Some additional thread-safety guarantees (a single-item enum is the recommended way to implement singletons in Java)
like image 109
soc Avatar answered Feb 25 '26 08:02

soc


The 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.

like image 40
Charlie Avatar answered Feb 25 '26 07:02

Charlie