Enumeration by dedicated class

Figure 324. Enumeration by instances Slide presentation Create comment in forum

Roadmap:

  • Define a dedicated class representing the enumeration.

  • Create exactly one instance per enumeration value.

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


Figure 325. 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();
}

Figure 326. switch no longer works! Slide presentation Create comment in forum
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 327. 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 328. Argument mismatch error Slide presentation Create comment in forum
// Class Driver

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

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

Figure 329. 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");

System.out.println(phpIntro.toString());
Lecture «PHP introduction» being
held each Illegal day instance: 
de.hdm_stuttgart.mi.sd1.
class_wrapper.Day@63961c42