Java Enums
What is
- Java Enums contain one or more enumerations.
- Enumerations are the first member to be declared in an enum.
- Java Enums are implicitly
public
,static
,final
references. - Enumerations are often confused with constants.
- Constants are implicitly immutable
public
,static
,final
Use Case Scenario
Casino Simulation Application
- Consider a
CasinoSimulationApplication
which simulates playing card-games.
Deck Class
- It follows that a
Deck
class, representative of aDeck
of cards, should be designed. - A
Deck
is made up of 52Card
s.
Card Class
- There are 13
Rank
s that aCard
can have. - There are 4
Suit
s that aCard
can have.
Rank Class
- A
Rank
has one of 13 names, and a respective integer value.Ace
has a value of1
.Two
has a value of2
.Ten
has a value of3
.Ten
has a value of4
.Ten
has a value of5
.Six
has a value of6
.Ten
has a value of10
.Jack
has a value of11
.Queen
has a value of12
.King
has a value of13
.
- Below is a base
Rank
class
public class Rank {
private final int primaryValue;
private final String name;
Rank(String name, int value) {
this.name = name;
this.value = value;
}
public String name() {
return name;
}
public int getValue() {
return value;
}
}
Suit Class
- A
Suit
has one of 4 names, and 1 of two colors.Hearts
have a color ofred
Diamonds
have a value ofred
Spades
have a value of12
Clubs
have a value of13
- Below is a base
Suit
class
public class Suit {
private final boolean isRed;
private final String color;
Suit(String name, String color) {
this.name = name;
this.color = color;
}
public String name() {
return this.name;
}
public String getColor() {
return this.color;
}
}
Design Implementations
Map Implementation
- Intuition may tell you leverage a map
- However, a map will actually convolute more than resolve anything.
- You can view the article discussing that implementation here.
Public Static References
- Intuition may tell you to create
public
static
references in a separateConstants
class. - While this is a much more elegant solution, it still produces many redundant expressions.
- You can view the article discussing that implementation here.
Enum Implementation
- The
Enum
implmentation is behaviorally identical to the aforementionedpublic
static
references.- This implementation adds syntactical sugar to shorten the redundancies of the expression.
Enum
s have implicit characteristics that allow more elegant expressions.