New "Typesafe ENUMS" What is the advantage of using an integer enumeration (int enjoy)?
This issue has detailed discussion in our book 21. Briefly said:
It provides compilation type security, and integer enumeration does not provide any type of security.
They provide an appropriate namespace for enumerated types - in an integer enumeration you must have a constant to get a namespace.
It is stronger-integer enumeration being compiled into the program, if you increase, delete or reset the constant order you must recompile your program.
The output value is included - if you print an integer enumeration, you will only get a number.
They are objects, you can put them in a collection.
They are essentially classes, so you can increase any attributes and methods.
Wow, it is so powerful! So what is the relationship between the new type of security enumeration language characteristics and the type of security in your book?
This feature is a simple support for the first language of type security mode. The code that is almost half-page, lengthy, and error-in support mode now looks like a statement in the enumeration in C / C :
ENUM season {winter, spring, summer, fall}
However, it is used up to the enumeration in C / C , you can use all the power we just discussed. It does even fix the main disadvantages of type security mode: you can use this new language feature and Switch statement together.
Can you give us an example of the powerful feature of type security enumeration?
of course can. The following this enumeration represents a US coin:
Public enum coin {
Penny (1), Nickel (5), DIME (10), Quarter (25);
COIN (int value) {this.value = value;
PRIVATE FINAL INT VALUE
Public int value () {return value;}
}
Look, how this constant declares how to call a constructor, enter an integer representation? Also, how does this value stored in a private variable with a public access method? This can hide the outline of what you can do.
Can you give me a class to use the ENUM you defined above?
I am preparing to say this. Below is a small example, it is used to output the values and colors of each of the documented menu.
Public class cointest {
Public static void main (String [] args) {
For (COIN C: coin.values)
System.out.println (C ": / T"
C.Value () "¢ / t" color (c));
}
Private Enum Coincolor {Copper, Nickel, Silver}
Private static coincolor color (coin c) {
Switch (c) {
Case coin.penny: return corncolor.copper;
Case coin.nickel: Return Coincolor.nickel;
Case coin.dime:
Case coin.quarter: returnoColor.silver;
DEFAULT: Throw new assertionerror ("Unknown Coin:" C);
}
}
}