Java 5 new features enumeration, Java 5 new features

Source: Internet
Author: User

Java 5 new features enumeration, Java 5 new features
1. Concept

First, enumeration is not a new technology, but a basic data type. It belongs to the value types of the two basic types, as shown below:


  


2. Why does enumeration exist?

Enumeration is very commonly used in real development, and its function is simple and pure: it defines a specification, it is to make the value of a variable of a certain type only be one of several fixed values, that is, to comply with its defined specifications. it allows the compiler to identify invalid values entered in the program during compilation, to some extent, preventing invalid type value errors during runtime.

For example, to define the variables of the day of the week, if the common variables 1-7 are used to represent Monday to Sunday, but some may be written as int weekday = 0. this kind of error can only be found at runtime, and compilation is okay. However, if enumeration is used to replace common variables, errors can be identified during compilation.

Enumeration itself is of course a class. Its definition is similar to that of a common class, and each enumerated variable is equivalent to an object of the class. The following describes the basic usage of enumeration, enumeration with constructor, and enumeration with abstract methods. As follows:


3. Basic use

Instance:

Public class EnumTest2 {public static void main (String [] args) {WeekDay weekDay2 = WeekDay. FRI; // use the 1: toString () method System. out. println (weekDay2); // output: FRI // use the 2: name () method System. out. println (weekDay2.name (); // output: FRI // use the 3: ordinal () method System. out. println (weekDay2.ordinal (); // output: 5 // use 4: Reflection of enumeration variables System. out. println (WeekDay. valueOf ("SUN "). toString (); // output: SUN // use 5: Obtain the enumerated length System. out. println (WeekDay. values (). length); // output: 7}/*** defines the enumeration class -- this is a subclass of the test class */public enum WeekDay {SUN, MON, TUE, WED, THI, FRI, SAT ;}}


4. Enumeration with Constructor

There are two requirements:

All things must be written after the enumerated variable

Ø the constructor must be private.

Usage:

When an enumerated variable is used, all the enumerated variables are instantiated and cached.

Which constructor is used for enumeration variables, like common classes, depends on the type and number of parameters.

Instance:

Public class EnumTest {public static void main (String [] args) {WeekDay weekDay = WeekDay. MON; System. out. println ("-------------"); WeekDay weekDay2 = WeekDay. TUE;/** output result: constructor 3 constructor 2 constructor 1 constructor 1 constructor 1 ------------- (end) * When MON is called above, the constructor of all enumeration variables is called. When TUE is called again, no call is made * indicating that when an enumeration variable is used, all enumeration variables are instantiated and cached; * when it is used again later, it will not be instantiated */}/*** to define the enumeration class -- this is a subclass of the test class */public enum WeekDay {// same as the normal class, which of the following constructor is used for enumeration variables depends on the type and number of parameters? // The following SUN will adopt constructor 3; MON uses constructor 2; the rest are constructed using the methods 1SUN (), MON (1), TUE (), WED, THI, FRI, SAT; // constructor 1: private WeekDay () {System. out. println ("constructor 1");} // constructor 2 private WeekDay (int day) {System. out. println ("constructor 2");} // constructor 3 private WeekDay (int day, int day2) {System. out. println ("constructor 3 ");}}

5. Enumeration with abstract methods

Logical Methods in enumeration classes will certainly involve all enumeration variables. A large number of if... Else statement. You can use the abstract method... Else statements are transferred into independent classes.

For example, in the following traffic light enumeration class, if you want to calculate the color of the next light, you must determine the general method. If the current "red light", then the next light is "green light "; if the current light is a "green light", the next light is a "yellow light "......; If an abstract method is used, a series of judgments can be transferred to independent classes. Instance:

/*** Defines the enumeration class */public enum TrafficLamp {// "{}" to indicate an anonymous subclass, so you can override the enumeration abstraction method. In this example, if .. else is converted to three anonymous subclasses RED (30) {public TrafficLamp nextLamp () {return GREEN ;}, GREEN (45) {public TrafficLamp nextLamp () {return YELLOW ;}, YELLOW (5) {public TrafficLamp nextLamp () {return RED ;}}; // abstract method-calculate the color of the next light public abstract TrafficLamp nextLamp (); private int time; // define the duration of the traffic light private TrafficLamp (int time) {this. time = time;} // constructor}

6. Common simulated enumeration classes

The following describes how to simulate an enumeration class using a common class.

Elements:

Ø private constructor

Simulate enumerated variables with public static member variables

Some public methods or

Instance:

Package TestPage; public abstract class WeekDay {// private constructor private WeekDay () {}// public static member variables SUN and MON simulate enumeration variables, "{}" indicates an anonymous subclass public final static WeekDay SUN = new WeekDay () {@ Overridepublic WeekDay nextDay () {return MON ;}}; public final static WeekDay MON = new WeekDay () {@ Overridepublic WeekDay nextDay () {return SUN ;}}; // abstract method-transfer the nextDay calculation logic public abstract WeekDay nextDay (); // use the if... else judgment/* publi C WeekDay nextDay () {if (this = SUN) {return MON;} else {return SUN ;}} * // public method public String toString () {return this = SUN? "SUN": "MON ";}}

7. Summary

Enumeration is a special "class". Enumeration variables are equivalent to objects of enumeration classes. It defines a specification so that the values of enumerated variables must comply with the defined specification and can only be one of several fixed values, this prevents invalid type value errors during running to a certain extent.

 


Java 50 new features

Do you have QQ to help me change some software? 0 ~ HOHO ~ \
This question should not be asked here

What is the difference between enumeration and string array in Java 5?

With the increasing popularity of computers, programs are not only used for numerical calculation, but also more widely used to process non-numerical data. For example: Gender, month, day of the week, color, unit name, education, occupation, etc., are not numerical data. In other programming languages, a value is generally used to represent a certain State. This processing method is not intuitive and easy to understand. If you can use words with corresponding meanings in natural language to represent a certain State in a program, the program will be easy to read and understand. That is to say, taking into account the possible values of a variable in advance, we try to use words with clear meanings in natural language to represent each of its values. This method is called the enumeration method, the type defined in this method is called Enumeration type.
 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.