1

I'm coming from c#, and find java's switch statement a bit confusing.

You can only switch on a character, yet you can switch on an enumeration.

Is this because it switches internally on the value?

Why would you want to add methods to an enumeration?

Erick Robertson
  • 32,125
  • 13
  • 69
  • 98
codecompleting
  • 9,251
  • 13
  • 61
  • 102

3 Answers3

7

It sounds like the assumption behind your question is false. You can switch on enum values, integer types (char, int, byte, etc.), or String instances.

Internally, all switches compile to one of two instructions, lookupswitch or tableswitch. Both instructions require that each case be labeled with a distinct integer. When you use an enum value, the "ordinal" of the value is used. When using String instances, the compiler inserts additional code to map each string to a unique value. Other types are used directly. You can read more about this in another answer.

Methods on an enum serve the same purpose as methods on any other object. You can use them to implement polymorphic behavior, or as simple accessors, or whatever.

Community
  • 1
  • 1
erickson
  • 265,237
  • 58
  • 395
  • 493
2

Regarding "Why would you want to add methods to an enumeration?"
In c# an enum is a restricted integer with some syntactic sugar, in java an enum is an actual class. There are really different. You can add a method to an enum for the same reason you add it to any other class, to make it do things! As an example, every time you use a switch oven an enum you could perfectly use a method on the enum instead of switch, and be more object oriented. And if you need to switch over the same enum in more than one place, you probably would be better of using a method
instead of doing

switch(planet){
   case Mars: doWhatMarsDo();break;
   case Earth: doWhatEarthDo();break;
}

you can write

planet.doYourThing();
Pablo Grisafi
  • 5,039
  • 1
  • 19
  • 29
1

Secondary question: because sometimes enums need methods, like to get properties, do calculations, etc. Enum methods are tremendously handy and allow some interesting games to be played.

Even the tutorial's example isn't overly-contrived, using enum properties and methods to good effect.

Community
  • 1
  • 1
Dave Newton
  • 158,873
  • 26
  • 254
  • 302