Enumeration by dedicated class
Roadmap:
-
Define a dedicated enumeration representing class.
-
Create exactly one class instance per enumeration value.
-
Enumeration value equality comparison by virtue of the
==
operator.
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.
Reverting to if .. else if ... required 🙄
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; } }
/** * 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; } }
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));
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 |