Image for 1, 2, 3, Enum

1, 2, 3, Enum

Enumeration is a way to easily represent a group of constants. We have a special type of class for this in Java called Enum. It's kind of a class; we have a constructor and it has some inherited methods from being an enum. But being a group of constants means that they are final. Actually enums are public, static and final. When would we want to use this though?

Enums can be a good way to represent ordinal values, such as VERY_LOW, LOW, MEDIUM, HIGH, VERY_HIGH. We can associate each enum with a different value. So let's write up the code for this example:


public enum Level {
VERY_LOW(1),
LOW(2),
MEDIUM(3),
HIGH(4),
VERY_HIGH(5);

public final int NUMBER;
Level(int number) {
NUMBER = number;
}
}


And in our main method we can illustrate how we could use an enum:

public class Main {
public static void main(String[] args) {

for (Level level : Level.values()) {
System.out.println(level + ": " + level.NUMBER);
}

}
}


This would give us the following result:


VERY_LOW: 1
LOW: 2
MEDIUM: 3
HIGH: 4
VERY_HIGH: 5



This has been a quick look at enum. See you next time! 😉