enum enumeration type in Java

insert image description here

knowledge introduction

In Java, enuman (enumeration) is a special data type used to define a set of named constants. Enumerated types allow you to create a fixed, predefined set of values ​​in your code that can be used throughout your program. Using enums can make your code clearer, more readable, and safer.

Java enumtypes, introduced in JDK 1.5, are a special form of a class that can thus have fields, methods, and constructors. The following is enuma detailed explanation about Java:

  1. Defining an enumeration type:
    Use enumkeywords to define an enumeration type. Enum types should be in a separate file, and usually in a separate Java class. Enumeration types are usually named in capital letters, and multiple words are separated by underscores.

    Example:

    public enum DayOfWeek {
          
          
        MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
    }
    
  2. Enumeration constants:
    In an enumeration type, use a comma-separated set of constants. These constants are unique throughout the program and are immutable and cannot be modified at runtime.

  3. Enum Methods and Fields:
    Like ordinary classes, enums can have fields, methods, and constructors. Each enumeration constant is an instance object that can call methods defined in the enumeration class.

    Example:

    public enum DayOfWeek {
          
          
        MONDAY("星期一"), TUESDAY("星期二"), WEDNESDAY("星期三"),
        THURSDAY("星期四"), FRIDAY("星期五"), SATURDAY("星期六"), SUNDAY("星期日");
    
        private String chineseName;
    
        // 枚举构造函数
        DayOfWeek(String chineseName) {
          
          
            this.chineseName = chineseName;
        }
    
        // 枚举方法
        public String getChineseName() {
          
          
            return chineseName;
        }
    }
    
  4. Using enumerated types:
    You can use constants of enumerated types in your program just like using ordinary static constants. Methods defined in enumerated types can also be called.

    Example:

    public static void main(String[] args) {
          
          
        DayOfWeek today = DayOfWeek.MONDAY;
        System.out.println("Today is " + today);  // 输出:Today is MONDAY
        System.out.println("Chinese name: " + today.getChineseName());  // 输出:Chinese name: 星期一
    }
    
  5. Enumerations in switch statements:
    Enumeration constants are often switchused in statements, which can increase the readability of the code.

    Example:

    public static void printDayType(DayOfWeek day) {
          
          
        switch (day) {
          
          
            case MONDAY:
            case TUESDAY:
            case WEDNESDAY:
            case THURSDAY:
            case FRIDAY:
                System.out.println("Weekday");
                break;
            case SATURDAY:
            case SUNDAY:
                System.out.println("Weekend");
                break;
        }
    }
    

Applicable scene

enum( enum) is useful in many situations. Here are some common scenarios where enums can be used:

  1. Represents a limited set of constants:
    Enumerations are used when you need to define a fixed and limited set of constants. For example, representing the day of the week, month, color, state, etc. are common scenarios where enums are used.

    public enum DayOfWeek {
          
          
        MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
    }
    
  2. Improves code readability:
    Using enums can make code more clear and readable. Enumeration constants have descriptive names, which can make code more self-explanatory than using plain integer or string constants.

  3. Avoid errors:
    Enum constants are determined at compile time and can only be one of the predefined values. This helps avoid using wrong values ​​and improves code robustness. At the same time, the intelligent prompt function of the IDE can also help programmers to choose the enumeration constant correctly.

  4. Used in switcha statement:
    When a multi-branch judgment is required for a specific type, the enumeration constant is switchvery useful in a statement, which improves the readability of the code.

  5. Limit the input range:
    When you need to limit the input range and ensure that the input value is a predefined value, the enumeration can well meet this demand.

  6. Representing a state machine:
    Enumeration constants can be used to represent different states in a state machine. For example, an order can have different states such as "Pending", "Paid", "Shipped", etc. These states can be represented by enumerations.

Say something from your heart:
Java enumis a special data type used to define a set of named constants. Overall, using enums can improve the readability, maintainability, and reliability of your code. Enums are a good choice if you need to define a fixed set of constants, or need to represent a finite, predefined set of values. It makes your code clearer, more readable, and reduces the potential for bugs. Of course, sometimes we ignore the definition of variables, or even use the enumeration type of enum, but this is a bad habit! The code needs to be standardized. We usually see the source code of some big guys, and the enum enumeration type is often used in appropriate situations. Therefore, we should also study hard and use it ourselves. We should not be intimidated and stop! Sometimes I also pick the persimmons and pinch them softly, which makes me learn very slowly, so let's encourage each other!

Guess you like

Origin blog.csdn.net/weixin_53742691/article/details/132128606