Consider the following (bad) Java,
implementing the "C style" enum pattern:
public class Coins {
public static final int PENNY = 1;
public static final int NICKEL = 5;
public static final int DIME = 10;
public static final int QUARTER = 25;
}
- Give example code that illustrates a type safety problem with
Coins
. Work through a range of expressions from
"probably ok" to "clearly wrong".
- What code would you need to turn a nickel into a string?
Explain how this could go wrong at runtime.
- What code would you need to iterate through the coins?
- Write a decent Java Enum for coins.
- Turn a nickle into a string.
- Iterate though the coins.
Consider Bloch's example:
// Abuse of ordinal to derive an associated value – DON’T DO THIS
public enum Ensemble {
SOLO, DUET, TRIO, QUARTET, QUINTET,
SEXTET, SEPTET, OCTET, NONET, DECTET;
public int numberOfMusicians() { return ordinal() + 1; }
}
Explain why it's wrong, fix it,
and add another enum with an overlapping number of musicians.