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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
It sounds like the assumption behind your question is false. You can switch on
enumvalues, integer types (char,int,byte, etc.), orStringinstances.Internally, all switches compile to one of two instructions,
lookupswitchortableswitch. Both instructions require that each case be labeled with a distinct integer. When you use anenumvalue, the “ordinal” of the value is used. When usingStringinstances, 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
enumserve the same purpose as methods on any other object. You can use them to implement polymorphic behavior, or as simple accessors, or whatever.