Reprint Please specify Source:http://blog.csdn.net/lhy_ycu/article/details/45332565
First, preface
Today we are talking about enumerations, hoping that through this blog you can have a more comprehensive understanding of enumerations. An enumeration is a class with a fixed number of instances (uppercase), which can be used to determine the number of States (such as: the mouse up or down, the IM message is unread), the number of types (such as: System, chat, add friend message, my his), Number of modes (reply, comment mode, swipe, full mode), etc. Enumerations and classes, as well as abstract classes, can implement interfaces, can contain internal classes, initialization blocks, it is worth noting that: the enumeration of the constructor, whether or not using private decoration, the default is always private decoration; Of course, the enumeration variable can also be used in the switch. Let's take a full look at the enumeration in Java by using an example.
Ii. Description of the case
(1) Example demo
/** * Modifier enum enum Name {*//immediately all instances of the enumeration in the first row (but actually creating an enumeration instance, the parameterless constructor is called by default). *} * * @author [* Reproduced yesterday *] [email protected] * @since version 1.0 * @datetime April 27, 2015 PM 8:36:44 */public enum Gende R {//MALE ("male") is equivalent to: Gender MALE = new Gender ("male");//list all enumerated values, that is, all possible instances of the enumeration--instance list//Womenmale The default is Womenmale () MALE ("Male"), FEMALE ("female"), Manmale (), Womenmale;private String name;//-the constructor, whether or not the private adornment is used, is always modified by the private gender () { SYSTEM.OUT.PRINTLN ("Non-parametric constructor method called ..."); Private Gender (String name) {System.out.println ("with parameter constructor method called ..." + name); this.name = name;} Note: The initialization block can only be modified by static. The code for the instance initialization block at compile time is extracted to the "front" of the constructor, so it takes precedence over the constructor {System.out.println ("instance initialization block ....");} When a class is loaded, it is implicitly executed after the class is initialized, and a JVM is initialized only once for a class. static {System.out.println ("Static/class initialization Block ..."); public void info () {System.out.println (the info method in the This + "enumeration is called");} /** * Enumeration in switch using--switch (byte/short/char/int/string/enumeration) * * @param gender */public static void Choosesex (gender gende R) {switch (gender) {//Pass an enumeration variable to switchcase MALE:System.out.println ("male ..."); Break;case FEMALE: System.out.println ("female ..."); Break;case MANMALE:System.out.println ("gay ..."); Break;case Womenmale: System.out.println ("lesbian ..."); break;default:break;}} Class A {{System.out.println ("A in instance initialization block ...");} public void info () {System.out.println (the info method in Class A is called ");}} public static void Main (string[] args) {//initialization block and constructor (no parameter or include parameter) are executed in the order of the instance list, followed by static (class) initialization block Gender g1 = Gender.male; Gender.choosesex (G1); G1.info ();//Create a parasitic class (inner Class) Instance A = G1.new a (); A.info ();//Print the enumeration variable G1 where the instance list is located, Starting from 0 System.out.println (g1.ordinal ());//Gender g2 = gender.female;//System.out.println (g2.ordinal ());// Prints all instances of the enumeration for (Gender g:gender.values ()) {System.out.println (g);}}}
========= Printing Results =============
Instance initialization block ....
Method with parameter construction called ... Man
Instance initialization block ....
Method with parameter construction called ... Woman
Instance initialization block ....
Non-parametric constructor method is called ...
Instance initialization block ....
Non-parametric constructor method is called ...
static/class initialization blocks ...
Men...
The info method in the MALE enumeration is called
A in the instance initialization block ...
The info method in the [email protected] class is called
0
MALE
FEMALE
Manmale
Womenmale
(2) Take a look at the use of abstract enumerations
The compiler will record the annotation information in the class file, and the JVM retains annotations when running the Java program, so the information of the annotations can be read through the reflection mechanism. @Retention (retentionpolicy.runtime)//annotation function above class @target (elementtype.type) public @interface ClassName {//declaration default value string Name () default "calculation";//Special value string value ();}
/** * Using abstract enumerations to emulate a arithmetic, you need to create an anonymous inner class to override the associated abstract method. * @author [* Reproduced yesterday *] [email protected] * @since version 1.0 * @datetime April 27, 2015 10:14:02 *///specifies which custom annotation class is used, if the Name is removed, the name defaults to: Computed @classname (name = "Enum", value = "arithmetic") public enum Calculator {ADD ("Zhang San") {@Overridepublic double eval (d Ouble x, double y) {return x + y;}},sub {@Overridepublic Double eval (double x, double y) {return x-y;}},multiply {@Overr Idepublic Double eval (double x, double y) {return x * y;}},divide {@Overridepublic double eval (double x, double y) {if (Y = = 0) {throw new ArithmeticException ("divisor cannot be 0");} return x/y;}}; Private String name;private Calculator () {System.out.println ("No parameter constructor is executed ..." + this);} Private Calculator (String name) {this.name = name; System.out.println ("with parameter constructor is executed ..." + this.name);} Public abstract Double eval (double x, double y);p ublic static void Main (string[] args) throws ClassNotFoundException {Calc Ulator C1 = Calculator.add; System.out.println (C1.eval (1, 2));//Calculator C2 = calculator.sub;//System. OUT.PRINTLN (C2.eval (1, 2));//Print some annotation information for this enumeration class<?> clazz = Class.forName ("Com.leo.enumation.Calculator"); ClassName cn = clazz.getannotation (Classname.class); System.out.println (Cn.name () + "," + Cn.value ());}}
(3) enumeration implementation Interface
Interface Idirection {void Pointdirection ();} /** * Enumeration Implementation Interface * * @author [* Reproduced yesterday *] [email protected] * @since version 1.0 * @datetime April 27, 2015 afternoon 11:01:50 */public en Um Orientation implements Idirection {EAST, WEST, south (), North, @Overridepublic void Pointdirection () { System.out.println ("point to--->" + this);} public static void Main (string[] args) {Idirection direction = Orientation.south;direction.pointdirection ();}}
Iii. Summary
About the enumeration in Java about the relevant knowledge points in general, after the update of internal classes, regular expressions, improve the quality of Java code some suggestions and so on, please pay attention!
Java Learning Series (22) Java Object-oriented enumeration