Java record -79-enumeration (Enums)

Source: Internet
Author: User

Enumeration (Enums)

JDK1.5 adds a completely new type of "class"-- enum type. For this JDK1.5 A new keyword enumis introduced. We can define an enumeration type like this.

public enum color{

Red,

White,

Blue

}

You can then use Color mycolor = color.red;

Enumeration types also provide two useful static methods for values () and valueOf (). We can use them very conveniently, for example:

For (Color c:color.values ())

System.out.println (c);

Defining an enumeration type is essentially defining a category, but a lot of detail is done by the compiler, so in some ways theenum keyword acts like a class or Interface.

enum "When you define an enumeration type, essentially the type you define inherits from the java.lang.enum instance final so you can't change them, they're also static Members, so you can use them directly by type name, and of course the most important of them are public public

The enumeration is simple to define and use:

Enum definition public enum Color {Red, white, blue}//enumeration using public class Colortest {public static void main (string[] args) {        Color MyColor = color.red;                System.out.println (MyColor);        For (Color c:color.values ()) {System.out.println (c); }    }}

Enumerating Common scenarios:

Public class enumtest {    public static void doop ( OPCONSTANT OP) {        switch (OP) {         case TURN_LEFT:             System.out.println ("Turn left");            break;         case TURN_RIGHT:             system.out.println ("Turn right");             break;        case SHOOT:             system.out.println ("shooting");             break;        }     }    public static void main (String[] args) {         doop (opconstant.shoot);     }}enum opconstant{    turn_left,  turn_right, shoot}


Java record -79-enumeration (Enums)

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.