Enums
Learning Objectives Covered
By the end of this lesson, you will be able to 1.) represent a set of predefined constants as an enum type and 2.) use a set of predefined constants contained in an enum type.
Learning Materials
Time Commitment
Approximately 1 hour
Read (Approximately 20-25 minutes)
Watch (Approximately 10 mins)
- Watch up to 9:30.
- The video defines
static
andfinal
. We are not expecting you to understand these concepts yet. We will get to them. We promise. - The term “package private” gets mentioned in this video, just think of it as
private
. - The
System.out.printf()
method is a fancy version ofSystem.out.print()
. The ‘f’ stands for format. In this course’s project you will learn about a very similar method calledString.format()
.
Try (Approximately 30 minutes)
In this try you will be completing an enum for the US months of the year called Month
.
Open the project in BlueJ and take a look at each class:
-
DisplayStyle
is a simple enum with two values:SHORT
andLONG
. This will be used byMonth
to help determine whichString
should be returned when getting the display value of a month. You will not need to edit this file. -
Month
is the enum you will be working to finish. It currently has one value,JANUARY
, and a few unimplemented methods that you will be completing. -
MonthTester
is a class with three methods in it that will help you test yourMonth
enum. As you write each method described below, you should uncomment the corresponding test code and run it to validate that your code is working as expected.
To finish the code for Month
you should complete the following methods:
NOTE: Implementing these methods may require you to add fields to your enum.
-
getLength()
: This method returns the number of days in the month. You can assume that February has 28 days. If you would like to tackle leap years as an added challenge, you can add a method that accepts a boolean that tells your method if the year is a leap year:getLength(boolean leapYear)
. -
plus(int numberOfMonths)
: This method calculates what month it will benumberOfMonths
after the current month. -
getDisplayName(DisplayStyle style)
: This method returns aString
value representing the month’s display value. Callers can request aSHORT
display style, otherwise theLONG
display style should be returned. A short display style should yield ‘Jan’ or ‘Aug’, while a long display should return ‘January’ or ‘August’. The short display style for June, July, and September should be 4 characters long, but the other short display for other months should be 3 characters long.