Link Search Menu Expand Document

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)

Enums


Watch (Approximately 10 mins)

Java Basics - Enums Part 2

  • Watch up to 9:30.
  • The video defines static and final. 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 of System.out.print(). The ‘f’ stands for format. In this course’s project you will learn about a very similar method called String.format().

Try (Approximately 30 minutes)

In this try you will be completing an enum for the US months of the year called Month.

The BlueJ project zipfile.

Open the project in BlueJ and take a look at each class:

  1. DisplayStyle is a simple enum with two values: SHORT and LONG. This will be used by Month to help determine which String should be returned when getting the display value of a month. You will not need to edit this file.

  2. 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.

  3. MonthTester is a class with three methods in it that will help you test your Month 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.

  1. 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).

  2. plus(int numberOfMonths): This method calculates what month it will be numberOfMonths after the current month.

  3. getDisplayName(DisplayStyle style): This method returns a String value representing the month’s display value. Callers can request a SHORT display style, otherwise the LONG 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.