Why Enumerate a Type?

Here's the older approach of simulating enumerations:

class Bread {    static final int wholewheat = 0;    static final int ninegrain = 1;    static final int rye = 2;    static final int french = 3;}

You would then declare an int variable and let it hold values from the Bread class, e.g.

int todaysLoaf = Bread.rye;

Drawbacks of using ints to enumerate

Using final ints to represent values in an enumeration has at least three drawbacks.

  • All the compiler tools (debugger, linker, run-time, etc.) still regard the variables as ints. They are ints. If you ask for the value of todaysLoaf, it will be 2, not “rye”. The programmer has to do the mapping back and forth mentally.

  • The variables aren't typesafe. There's nothing ...

Get Just Java™ 2 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.