Sunday 13 March 2016

The Java Language: Enumerations and switch statements

Enumerations are intended to replace much of the usage of integer constants for situations like the one just discussed with a typesafe alternative. Enumerations use objects as their values instead of integers but preserve the notion of ordering and comparability. We’ll see that enumerations are declared much like classes and that the values can be “imported” into the code of your application to be used just like constants. For example:

 enum Size { Small, Medium, Large }  
You can use enumerations in switches in the same way that the previous switch examples used integer constants. In fact, it is much safer to do so because the enumerations have real types and the compiler does not let you mistakenly add cases that do not match any value or mix values from different enumerations.
 // usage  
 Size size = ...;  
 switch ( size ) {  
 case Small:  
 ...  
 case Medium:  
 ...  
 case Large:  
 ...  
 }  
We will see in more detail about enumerations.

0 comments:

Post a Comment