Java enumeration class

Source: Internet
Author: User

Java enumeration class
I. Sample Code for several enumeration Classes 1. Simplest enumeration class

Enum Nuber {One, Two} // although the syntax structure of enum is different from that of class, a class file is generated after compilation by the JVM compiler. This class file is decompiled to show that a class is actually generated, which inherits java. lang. Enum <E>. Each class has a default no-argument constructor, so no constructor can be added here.
2. General enumeration usage
Public enum Person {// The enum instance must be written at the top of the enumeration class. Otherwise, the compiling error WORKER (0, "WORKER"), STUDENT (1, "STUDENT") is reported "); // If You Want To define a method, add one after the last enum instance; // encapsulate private int index; private String desc; // there must be a constructor that matches the structure of the enum instance with private Person (int index, String desc) {// The access modifier of the constructor here has no difference in accessibility regardless of whether it is declared as private. However, to clarify the meaning, we recommend that you add this. index = index; this. desc = desc ;}}

 

Ii. Enumeration Method 1. values () method. An array of enum instances is returned. The elements in the array strictly keep the order in which enum is declared. 2. ordinal (), returns the Order declared by this enum instance in enum (starting from 0) 3. compareTo () method, compares the order difference 4 and equals () declared in enum () equivalent to = 5, name () is equivalent to toString (), returns the name of the enumerated instance

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.