This is the 15th day of my participation in the August More Text Challenge. For details, see:August is more challenging

Java enumeration (enum)

Java enumeration is a special class that generally represents a set of constants, such as the four seasons of a year, the 12 months of a year, the seven days of a week, the directions southeast, northwest, and so on.

Java enumeration classes are defined using the enum keyword, and constants are separated by commas.

For example, define an enumeration class for a color.

enum Color 
{ 
    RED, GREEN, BLUE; 
} 
Copy the code

Color constants are RED, GREEN, and BLUE, indicating RED, GREEN, and BLUE respectively.

/** * java enum */
//enum Color
/ / {
// RED, GREEN, BLUE;
// // constructor
// private Color()
/ / {
// System.out.println("Constructor called for : " + this.toString());
/ /}
//
// public void colorInfo()
/ / {
// System.out.println("Universal Color");
/ /}
/ /}
enum Color{
    RED{
        public String getColor(a){// Enumeration objects implement abstract methods
            return "Red";
        }
    },
    GREEN{
        public String getColor(a){// Enumeration objects implement abstract methods
            return "Green";
        }
    },
    BLUE{
        public String getColor(a){// Enumeration objects implement abstract methods
            return "Blue"; }};public abstract String getColor(a);// Define abstract methods
}
public class Obj_6 {
    public static void main(String[] args) {
        / / call the values ()
        Color[] arr = Color.values();
 
        // Iterate over enumeration
        for (Color col : arr)
        {
            // View the index
            System.out.println(col + " at index " + col.ordinal());
            System.out.println(col.getColor());
        }
 
        // Use valueOf() to return an enumeration constant, or IllegalArgumentException if it does not exist
        System.out.println(Color.valueOf("RED"));
        try {
            System.out.println(Color.valueOf("red"));
        }catch(Exception e){ System.out.println(e); }}}Copy the code

Methods values(), ordinal(), and valueOf()

The enumeration class defined by enum inherits the Java.lang. enum class by default, and supports the java.lang.Seriablizable and java.lang.Com interfaces parable.

The values(), ordinal(), and valueOf() methods are in the java.lang.enum class:

  • Values () returns all the values in the enumerated class.
  • The ordinal() method finds the index of each enumeration constant, just like an array index.
  • The valueOf() method returns an enumeration constant with the specified string value.

Enumerating class members

Enumerations can have their own variables, methods, and constructors just like ordinary classes. Constructors can only use private access modifiers, so they cannot be called externally.

Enumerations can contain either concrete or abstract methods. If the enumeration class has an abstract method, then every instance of the enumeration class must implement it.

On methods of enumeration

In the enum, some basic methods are provided:

  • values(): Mandatory enum Array of instances. The elements in the array are in the exact order in which they were declared in the enum.
  • name(): Returns the instance name.
  • ordinal(): returns the order in which instances are declared, starting with 0.
  • getDeclaringClass(): Mandatory Enum Type of the instance.
  • equals(): Determines whether the objects are the same.

You can use == to compare enum instances.

In addition, java.lang.enum implements the Comparable and Serializable interfaces, so compareTo() methods are also provided.

Features of enumerations

The properties of enumerations boil down to this:

Basically, you can think of enUms as regular classes, except that they cannot be inherited.

But this sentence needs to be understood in pieces, so let’s break it down.

The basic features

If no method is defined in the enumeration, you can also add a comma, semicolon, or nothing after the last instance.

If no method is defined in the enumeration, the enumeration value defaults to an ordered value starting at 0. For the Color enumeration type, the constants are RED: 0, GREEN: 1, and BLUE: 2.

Methods can be added to an enumeration

Enumerated values, as mentioned in the concepts section, default to ordered values starting at 0. Here comes the problem: how to explicitly assign values to enumerations.

(1) Java does not allow the use of = to assign values to enumerators

If you have touched C/C++, you will naturally think of the assignment symbol =. In C/C++, enum can be explicitly assigned to an enumeration constant using the assignment symbol =; Unfortunately, the Java syntax does not allow you to use the assignment symbol = to assign values to enumerators.

Example: enumeration declaration in C/C++ language

typedef enum {
    ONE = 1,
    TWO,
    THREE = 3,
    TEN = 10
} Number;
Copy the code

(2) Enumeration can add ordinary methods, static methods, abstract methods, construction methods

Java can’t directly assign values to instances, but it has a better solution: add methods to enums to indirectly implement explicit assignment.

When you create an enum, you can add multiple methods to it, and you can even add constructors to it.

Note one detail: If you want to define methods for an enum, you must add a semicolon to the end of the last instance of the enum. In addition, in enUms, the instance must be defined first; fields or methods cannot precede the instance. Otherwise, the compiler will report an error.