So far, we've just used the simplest syntax to define enumeration types, in fact enumeration types can do more, and in Tiger's definition, enumerations are a new type that allows represented to represent a particular piece of data that is capable of most functions of a common class, such as defining its own constructors, methods, properties, and so on. This is also the difference between Java and C + + or Pascal, where enumerated types represent numbers of type int, but enumerations in Java are more like a class.
Next, we'll enrich our enumeration types.
The enumeration type that contains five business days is defined earlier, but the action that is actually performed on each weekday is in the Printweekday method in the other class. Assuming that we have analyzed that the operation of the working day should belong to the enumeration type weekday, we can transform the enumeration type as follows:
public enum weekday { MONDAY, TUESDAY, WENSDAY, THURSDAY, FRIDAY; /** * print different information depending on the day of the week. */ public void printweekday () { switch (This) { case monday: syStem.out.println ("today is monday!"); break; case tuesday: system.out.println ("today is tuesday!"); break; case wensday: system.out.println ("today is wensday!"); break; case thursday: system.out.println ("today is thursday!"); Break; case friday: system.out.println ("Today is friday! "); break; default: &Nbsp; throw new assertionerror ("Unexpected value: " + this); } }} //test program for (Weekday weekday: enumset.allof (weekday.class)) { system.out.println ("the message is : " + Weekday.printweekday ()); }
Now that the enumeration type operation has become much more plump, we have added a Printweekday method to the enumeration type weekday, and you can use the WeekDay.MONDAY.printWeekDay () method to output the information.
Enumeration types also allow you to define your own constructors, which allows enumeration constants to initialize more information. Take a look at the enumeration type DatabaseType that we mentioned in the Enummap and Enumset article, which holds all the database types that are now supported. But it is only a "code name", because the information related to the database is fixed to an application, so it is more appropriate to put the data in the enumeration type itself in accordance with the design habits.
public enum databasetype{ mysql (" Com.mysql.jdbc.Driver ", " Jdbc:mysql://localhost/mydb "), oracle ("Oracle.jdbc.driver.OracleDriver", "Jdbc:oracle:thin: @localhost: 1521:sample"),           DB2 ("Com.ibm.db2.jdbc.app.DB2Driver", "Jdbc:db2://localhost:5000/sample"), sqlserver ("Com.microsoft.jdbc.sqlserver.SQLServerDriver", "jdbc:microsoft:sqlserver:// Localhost:1433;databasename=mydb "); private string driver; private String url; //a custom constructor, which is a driver, url assignment DatabaseType (String driver,string url) { this.driver = driver; this.url = url; } /** * Get the databaseDrive * @ return */ public String Getdriver () { return driver; } /** * Get database Connection URL * @return */ public string geturl () { return url; }} //test Program for ( Databasetype databasetype: enumset.allof (Databasetype.class)) { system.out.println ("the driver is : " + Databasetype.getdriver ()); System.out.println ("the url is : " +databasetype.geturl ()); }
Did you notice how the enumeration constants in the example declare that they were initialized with a custom constructor? Only the data used for initialization needs to be placed in parentheses after the enumeration constant name.
Now that we have designed two content-rich enumeration types, the use of enumeration types has become much more natural. You might think that there is little difference between enum types and classes. However, there are many limitations to enum types, and you must follow them when implementing your own enumeration types.
Attention:
1. Enumeration types cannot use the extends keyword, but you can use the Implements keyword. This allows us to extract the behavior common to different enumeration types into an interface to standardize the behavior of enumeration types.
2. A custom constructor for an enumeration type cannot overwrite the constructor that is executed by default, and it follows the default constructor.
3. The custom constructor for the enumeration type must be private. You don't need to add the private keyword on the constructor, the compiler will do it for us.
4. The definition of enumerated constants in enumeration types must be placed at the top, followed by the definition of variables and methods.
Template method
Before we talk about this topic, we need to look at the rewritten Printweekday method, which is a bit more weekday in that case, but it's a bit cumbersome to use switch to judge the enumeration constants individually to customize different behaviors. If you add a new enumeration constant for weekday, if you forget to add a case flag for it in switch at the same time, even if you have the default flag to prompt for an error, you can only find it after running.
What can I do better? As we've learned before, enumerations are a special class that can have methods and properties, and each declared enumeration is an instance of this enumeration type. So can we use "template method mode" to transform this enumeration class? Of course! Let's refactor that example into the following way:
public enum weekday { MONDAY{ @ override public void printweekday () { system.out.println ("today is monday!"); } }, tuesday{ @Override public void printweekday () { system.out.println ("Today Is tuesday! "); } }, WENSDAY{ @Override public Void printweekday () { system.out.println ("today is wensday!"); } }, THURSDAY{ @Override public void printweekday () { System.out.println ("Today is thursDay! "); } }, FRIDAY{ @Override public void printweekday () { &Nbsp; system.out.println ("today is friday!"); } }; /** * print different information depending on the day of the week */ public abstract void printweekday (); }
First, we change the method Printweekday to an abstract method, and then we implement the abstract method defined in the enumeration type in each enumeration constant. In this way, each time you add a new enumeration constant for an enumeration type, you must implement the abstract method defined in the enumeration type, or the compiler prompts an error. The reason this can be done is that the virtual machine creates each enumerated constant declared in the enumeration type as a subclass of a separate enumeration type.
In this way, with the static import in Tiger, the caller's code can be written like this:
Monday.printweekday (); Tuesday.printweekday ();//or better...getweekday (). Printweekday ();
This code is obviously more than the common if (WeekDay = = Weekday.monday) {...} else if (WeekDay = = Weekday.tuesday) Else {...} The form is much stronger, they are easy to read, easy to expand and maintain.
Reverse Lookup
As mentioned earlier, enumerations can also be custom constructors, and you can use properties to correlate more data. What if we have such a need? --we need to get the corresponding enumeration items based on the associated data, such as the following:
Public final enum Status {Waiting (0), Ready (1), skipped ( -1), completed (5); private int code; Private Status (int code) {This.code = code; } public int GetCode () {return code;}}
Here each status corresponds to a code,waiting corresponding to 0, while the completed corresponds to 5. What do I do if I want to get waiting by 0?
It is also simple to use a static JAVA.UTIL.MAP to associate code with an enumeration, just like this:
Public final enum status { waiting (0), ready (1), skipped ( -1), completed (5); private static final map<integer,status> lookup = new hashmap<integer,status > (); static { for (Status s : enumset.allof (status.class)) { lookup.put (S.getcode (), s); } } public Static status get (Int code) { return lookup.geT (code); } private int code; private status (Int code) { this.code = code; } public int getcode () { return code; }}
The static method get (int) provides the reverse lookup capability in the requirements, while the static block uses Enumset to assemble the map-making map, over!
Summary: Use enumerations, but do not misuse!
One of the dangers of learning any new language is the madness of using the new grammatical structure. If you do this, your code will suddenly have a 80% of generics, callouts, and enumerations. Therefore, it should only be used where enumeration is appropriate. So where does the enumeration apply? A common rule is any place where constants are used, such as where a constant is being toggled with a switch code. If there is a single value (for example, the maximum size of a shoe, or the maximum number of monkeys in a cage), leave the task to a constant. However, if you define a set of values, and any of these values can be used for a particular data type, it is best to use enumerations in this place.
Reprint to: http://blog.csdn.net/shimiso/article/details/5909239
This article is from the "Ciyo Technology sharing" blog, please be sure to keep this source http://ciyorecord.blog.51cto.com/6010867/1934197
Enumeration in Java (ii)