Java Enumeration Class enum introduction _java

Source: Internet
Author: User
Tags first row

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

1. If there is a constructor, it must be decorated with private.
2. An enumeration class cannot derive a child class.
3. Enumeration class All instances must display the definition in the first row. These instances are automatically added to the public static final modification by the system without the programmer displaying the definition.
4. Enumeration classes provide the values () method by default to facilitate traversal of all enumerated values

Methods in an enum (methods provided by the Enum):

Public final int compareTo (E o) compares enumerated values of the same type
The public final int ordinal () returns the indexed value of the enumeration, with the first enumeration value starting at zero.
Public final String name () returns the enumeration instance name
Public String toString () returns an enumerated output name

Traffic light Example

 public enum TrafficLight {red), yellow ("yellow"), Green ("green");
  private String name;
  Private TrafficLight (String name) {this.name = name;
  Public String GetName () {return name;
      public void Jude (TrafficLight light) {switch (light) {case RED:System.out.println ("Stop");
    Break
      Case YELLOW:System.out.println ("Go");
    Break
      Case GREEN:System.out.println ("Wait");
    Break
    Default:break; } public static void Main (string[] args) {for (TrafficLight e:trafficlight.values ()) {System.out.print
    ln (e.name ()); }
  }
}
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.