The Java Enumeration class enum explanation

Source: Internet
Author: User

Enum class Enum was introduced by JDK1.5, which was preceded by the public static final int Enum_value instead of the enumeration class. Enum class Enum is a special class that inherits the class Java.lang.Enum by default. Like other ordinary classes, an enum can have member variables, methods, constructors, or one or more interfaces, the difference being:

    • If there is a constructor, it must be decorated with private.
    • An enumeration class cannot derive subclasses.
    • All instances of an enumeration class must display the definition on the first line. The system automatically adds public static final adornments to these instances without requiring the programmer to display the definitions.
    • The enumeration class provides the values () method by default, which makes it easy to traverse all enumerated values

Methods in Enum (the method provided by the enum):

Public final int compareTo (E o) Compares enumeration values of the same type
Public final int ordinal () returns the index value of the enumeration, with the first enumeration value starting from zero.
Public final String name () returns the enumeration instance name
Public String toString () returns the enumeration yield name

Traffic light Example

 Public enumTrafficLight {RED ("Red"), YELLOW ("Yellow"), GREEN ("Green");PrivateString name;Private TrafficLight(String name) { This. name = name; } PublicStringGetName() {returnName } Public void Jude(TrafficLight Light) {Switch(light) { CaseRED:System.out.println ("Stop"); Break; CaseYELLOW:System.out.println ("Go"); Break; CaseGREEN:System.out.println ("Wait"); Break;default: Break; }    } Public Static void Main(string[] args) { for(TrafficLight e:trafficlight.values ())        {System.out.println (E.name ()); }    }}

The Java Enumeration class enum explanation

Related Article

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.