Enumeration by dedicated class

Figure 348. Enumeration by class instances Slide presentation Create comment in forum


  • Define a dedicated enumeration representing class.

  • Create exactly one class instance per enumeration value.

  • Enumeration value equality comparison by virtue of the == operator.

Figure 349. Class instance per enumeration value Slide presentation Create comment in forum
public class Day {

  static public final Day
    MONDAY    = new Day(),
    TUESDAY   = new Day(),
    WEDNESDAY = new Day(),
    THURSDAY  = new Day(),
    FRIDAY    = new Day(),
    SATURDAY  = new Day(),
    SUNDAY    = new Day();

Note: Class without instance attributes.

Figure 350. switch no longer works Slide presentation Create comment in forum

Reverting to if .. else if ...

public static String getDaysName(final Day day) {
  if (MONDAY == day) {  // Switch no longer possible, sigh!
    return "Monday";
  } else if (TUESDAY == day) {
  } else if (SUNDAY == day) {
    return "Sunday";
  } else {
    return "Illegal day instance: " + day;

Figure 351. Re-writing getPrice() Slide presentation Create comment in forum
 * Charge double prices on weekends
 * @param day Day of week
 * @param amount
 * @return the effective amount depending on day of week.
static public int getPrice(final Day day, final int amount) {
  if (Day.SATURDAY == day || Day.SUNDAY == day) {
    return 2 * amount;
  } else {
    return amount;

Figure 352. Compile time argument mismatch error Slide presentation Create comment in forum

Preventing method argument order mismatch:

// Class Driver

// o.K.
System.out.println(Screwed2.getPrice(Day.SUNDAY,  2));

// Argument mismatch causing compile time type violation error
System.out.println(Screwed2.getPrice(2, Day.SUNDAY));

Figure 353. Pitfall: Creating an undesired instance Slide presentation Create comment in forum
Class Screwed:

final Day PAST_SUNDAY = new Day();

final Lecture phpIntro = new Lecture(
     PAST_SUNDAY, "PHP introduction");

Lecture «PHP introduction» being
held each Illegal day instance: