In-depth enumeration enum understanding

Enumeration enum explanation



foreword

Enumerations generally represent a set of constants, such as spring, summer, autumn and winter, southeast, northwest, and so on.


1. Example: enumeration of seasons

1. Declaring an enumeration

Enumeration represents a limited number of instantiated objects of a class. For example, when it comes to seasons, you can only list four situations: spring, summer, autumn, and winter; when it comes to days of the week, you can only list seven situations from Monday to Sunday .

enum SeasonEnum {
    
    
    /*
     *枚举春、夏、秋、冬四种季节
     */
    SPRING,SUMMER,AUTUMN,WINTER;
}

Enumerations are allowed to be defined outside and inside the class, and files under the same project can also be referenced, just import before calling.

// 外部
enum MyEnum {
    
    }

public MyClass {
    
    }

// 内部
public MyClass {
    
    
enum MyEnum {
    
    }

}

// 引用
// 文件enums.MyEnum.java
package enums;
enum MyEnum {
    
    }

// 文件MyClass.java
import *.enums.SeasonEnum;
public MyClass {
    
    }

If there is an enum with the same name at the same time, the internal one of the class will overwrite the external one; the referenced one will overwrite the above two, and if the enum with the same name already exists elsewhere in the project, a compilation error will be reported until the .java file where the enum is located is imported correctly.

2. Enumeration call

public class Main {
    
    
    public static void main(String[] args) {
    
    
        System.out.println(SeasonEnum.SPRING);
    }
}

Result: SPRING

Enumeration enum is a special kind of class, and the default is mandatory to be specific, dynamic, and non-inheritable (abstract, static, and final modifications are not allowed, and a compilation error will be reported);

Enumerations have the same rules as classes in .java files: at most one class (enum) is modified by public, and the class (enum) must be consistent with the name of the .java file.

3. The nature of enumeration

Each enumeration is implemented internally by class, and all enumeration values ​​are public static final.
The above enumeration class SeansonEnum conversion is implemented in the internal class:

class SeasonEnum {
    
    
     public static final SeasonEnum SPRING = new SeasonEnum();
     public static final SeasonEnum SUMMER = new SeasonEnum();
     public static final SeasonEnum AUTUMN = new SeasonEnum();
     public static final SeasonEnum WINTER= new SeasonEnum();
}

This can explain why SeasonEnum is forced to be dynamic by default (static classes cannot be instantiated - not new).
As for why it is final, final means non-inheritable, and the modified class cannot have subclasses. A subclass itself represents an extension of the specification of the parent class. The enumeration itself is a concrete implementation of the complete specification, and if the subclass inherits the enumeration, it will put the cart before the horse.

4. values(), ordinal(), and valueOf() methods

Methods that exist by default in the enumeration (can be called without customization).
The enumeration class defined by enum inherits the java.lang.Enum class by default and implements the java.lang.Serializable and java.lang.Comparable interfaces.

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

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

example

enum SeasonEnum {
    
    
    // 此处的SPRING相当于SPRING()无参构造方法
    // 在{}代码块中要具体实现所有的抽象方法
    SPRING {
    
    
        @Override
        public void months() {
    
    
            System.out.println("This season includes March, April and May.");
        }

    },
    // 此处是调用SUMMER(String)构造方法
    SUMMER("hot") {
    
    
        @Override
        public void months() {
    
    
            System.out.println("This season includes June, July and August.");
        }

    }, AUTUMN {
    
    
        @Override
        public void months() {
    
    
            System.out.println("{This season includes September, October and November.");
        }

    }, WINTER {
    
    
        @Override
        public void months() {
    
    
            System.out.println("This season includes December, January and February.");
        }

    };

    // 变量的声明和普通类一样
    // 建议充分封装对象,使用private修饰,对外提供get()、set()方法。
    private String description;

    // 有参构造
    SeasonEnum(String adjective) {
    
    
        this.description = adjective;
        System.out.println("Constructor called for : " + this.toString());
    }

    // 构造方法,不写private也不会报错
    // 无参构造,如果没有声明任何一个构造方法则会默认生成一个无参构造
    SeasonEnum() {
    
    
        System.out.println("Constructor called for : " + this.toString());
    }

    public void descriptor() {
    
    
        System.out.println("This season is " + getDescription() + ".");
    }

    public String getDescription() {
    
    
        return description;
    }

    // 抽象方法,每个枚举对象中必须具体实现这个方法,否则会报编译错误
    // 抽象方法只能声明在抽象类里,但enum自己声明抽象方法,自己具体实现,这也是enum的特殊之处之一
    public abstract void months();
}

public class Main {
    
    
    public static void main(String[] args) {
    
    
        SeasonEnum season1 = SeasonEnum.SPRING;
        System.out.println(season1);
        season1.descriptor();
        season1.months();

        SeasonEnum season2 = SeasonEnum.SUMMER;
        season2.descriptor();
        season2.months();
    }

}


The output of executing the above code is:

Constructor called for : SPRING
Constructor called for : SUMMER
Constructor called for : AUTUMN
Constructor called for : WINTER
SPRING
This season is null.
This season includes March, April and May.
This season is hot.
This season includes June, July and August.

5. Iterate through enumeration elements

The elements of an enumeration can be iterated using the for statement:

example

enum SeasonEnum {
    
    
    SPRING, SUMMER, AUTUMN, WINTER;
}

public class MyClass {
    
    
    public static void main(String[] args) {
    
    
        for (SeasonEnum season : SeasonEnum.values()) {
    
    
            System.out.println(season);
        }
        
    }
    
}

The output of executing the above code is:

SPRING
SUMMER
AUTUMN
WINTER

6. Use enumeration class in switch

Enumeration classes are often used in switch statements:

example

enum SeasonEnum {
    
    
    SPRING, SUMMER, AUTUMN, WINTER;
}

public class MyClass {
    
    
    public static void main(String[] args) {
    
    
        SeasonEnum season= SeasonEnum.SPRING;

        switch (season) {
    
    
            case SPRING:
                System.out.println("春天");
                break;
            case SUMMER:
                System.out.println("夏天");
                break;
            case AUTUMN:
                System.out.println("秋天");
                break;
            case WINTER:
                System.out.println("冬天");
                break;
            default:
                break;
        }

    }

}

The output of executing the above code is:

spring


Summarize

Enumerations are a special kind of class, the difference being:

  1. A limited number of instantiated objects are created internally, and no new objects can be created.

Because the authority to instantiate the object is in your own hands (the construction method is private).

  1. When calling, it directly calls the instantiated static object, and enum itself completes all the work after creating all the enumeration objects.
  2. If you want methods with the same name in different instances of the enumeration to implement different content, you can declare an abstract method, and the final implementation of the abstract method in each instance is independent of each other.

Enum can declare abstract methods, and abstract methods can only be declared in abstract classes;
enum can instantiate objects, and only non-abstract concrete classes can be instantiated.
Seemingly contradictory.
Personally, I prefer enum to be a concrete class rather than an abstract class. Abstract classes cannot be instantiated, and the most important product of enum is the instantiated object.
The abstract method in enum is forced to be implemented in each object, which is the designer's final solution to the contradiction, and it is also one of the key points that distinguish enum from class.
There are many contradictions in a programming language, and the designer will definitely give a final rule, so you only need to understand the final rule, and you don’t have to get entangled. The analogy is just for understanding, don’t be bound by it.

Guess you like

Origin blog.csdn.net/War_wick/article/details/127793442