enumerate
In the past, we must replace the enumeration with the integer constant, with the release of J2SE 5.0, this method is finally not returned.
A simple enumeration type is defined as follows:
Public enum weather {sunny, rainy, cloudy}
Enumeration can be used in the switch statement:
Weather weather = weather.cloudy; switch (weather) {copy sunny: system.out.println ("it's sunny"); Break; Case Cloudy: System.Out.println ("It's Cloudy); Break; Case Rainy: System .out.println ("it's rainy"); Break;}
Enumeration Types can have their own constructor, but must be private, or other methods of definition, such as the following code:
Public Enum Weather {Sunny ("IT IS Sunny", Rainy ("IT IS Rainy"), Cloudy ("IT IS Cloudy"); Private String Description; Private Weather (String Description) {this.description = description;} public String description () {return this.description;}}
The following segment is a use of this enumeration:
For (WEATHER W: WEATHER.VALUES ()) {system.out.printf ("Description of% s IS /"% s / "./ n", w, w.description ());} weather weather = weather. Sunny; System.Out.println (Weather.Description () "Today");
If we have an enumeration type, it means that four operations, we hope to define a method, do different calculations for different values, then we can define:
Public Enum Operation {Plus, Minus, Times, Divide; // DO Arithmes, Divide; // do arithmetic op reported by this constant double {switch (this) {copy plus: returnix x y; case minus: returnx x - y; Case Times: Return X * Y; Case Divide: Return X / Y;} throw new assertionError ("Unknown Op: this);}}
The problem written is that if you don't have the final line to throw an abnormal statement, you cannot pass it. And if we want to add a new operation, we must always remember to add the corresponding operation to Eval. If you forget, you will throw an exception.
J2se 5.0 provides a solution to this problem, that is, you can declare the Eval function as Abstract, then write different implementations for each value, as shown below:
Public Enum Operation {Plus {Double Eval (Double X, Double Y) {Return X Y;}}, minus {Double Eval (Double X, Double Y) {Return x - y;}}, Times {Double Eval (double X, double y) {return}}, DiVide {Double Eval (double x, double y) {return x / y;}}; Abstract Double eval (double x, double y);}
This avoids the two problems mentioned above, but the amount of code has increased, but with the improvement of various Java development IDEs in the future, the problem should be diluted.