enum Constructors and Methods
enum Recap
An enum is a type of class. It represents a group of named constants. They are used when we know all the possible values, such as in the example of the directions for the robot. Other examples might include:
- list of menu options,
- suits in a deck of cards, or
- the primary colors (red, orange, yellow, green, blue, and purple).
Learn more:
Constructors
There are times when we want values to be associated with the different constants of an enum. For example, if we have directions for a robot of NORTH, SOUTH, EAST, and WEST, we may also want to include the number of degrees represented by each of these. Since enum is a type of class, it can include instance variables, constructors, and methods. The associate degree values are tied to the directions. We can include an instance variable called degrees and have a constructor that will assign degrees to the corresponding values.
General Format
Methods
You can also add accessor, mutator, and other methods to the enum.
Your Turn
Let's try it in the Java Playground.
- Read through the enum for the robot below and run the code.
- Create a new enum for a Suit (HEARTS, SPADES, CLUBS, DIAMONDS)
- Create a new enum for a FaceOfCard (ACE, TWO, THREE, ... TEN, JACK, QUEEN, KING) with an instance variables:
cardValue(Ace, 2 - 9 are worth 5; 10, Jack, Queen, King are worth 10)isFaceCard(Ace, 2 - 10 are false; Jack, Queen, and King are true)- add accessor methods to return the values of
cardValueandisFaceCard