O'Reilly logo

Just Java™ 2 by Peter van der Linden

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required