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,finalreferences. - Enumerations are often confused with constants.
- Constants are implicitly immutable
public,static,final
Use Case Scenario
Casino Simulation Application
- Consider a
CasinoSimulationApplicationwhich simulates playing card-games.
Deck Class
- It follows that a
Deckclass, representative of aDeckof cards, should be designed. - A
Deckis made up of 52Cards.
Card Class
- There are 13
Ranks that aCardcan have. - There are 4
Suits that aCardcan have.
Rank Class
- A
Rankhas one of 13 names, and a respective integer value.Acehas a value of1.Twohas a value of2.Tenhas a value of3.Tenhas a value of4.Tenhas a value of5.Sixhas a value of6.Tenhas a value of10.Jackhas a value of11.Queenhas a value of12.Kinghas a value of13.
- Below is a base
Rankclass
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
Suithas one of 4 names, and 1 of two colors.Heartshave a color ofredDiamondshave a value ofredSpadeshave a value of12Clubshave a value of13
- Below is a base
Suitclass
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
publicstaticreferences in a separateConstantsclass. - 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
Enumimplmentation is behaviorally identical to the aforementionedpublicstaticreferences.- This implementation adds syntactical sugar to shorten the redundancies of the expression.
Enums have implicit characteristics that allow more elegant expressions.