What is enumeration?

What is enumeration?

Enum is a special class (but enum is a class). It is convenient to define constants using enumerations. For
example, to design an enumeration type Four Seasons, four constants need to be defined inside. The constants are written in uppercase
public enum Season { SPRING, SUMMER,AUTUMN,WINTER; }In this way, the switch statement can be used to judge. For example, when the current season is Season, it is spring, and so on;


If you need to assign values ​​to certain types of seasonal attributes, do not use enumerations, no matter you define int attributes, use 1-4 to represent the four seasons, or write directly in Chinese "spring", "summer", "autumn", "winter" "Means four seasons, there may be values ​​outside the range of 5 or "spring".

But by using enumeration, you can specify the range to "SPRING, SUMMER, AUTUMN, WINTER", so that values ​​outside the range can be avoided.
example:

// 定义一个枚举类型 季节
enum Season {
    
    
    SPRING,SUMMER,AUTUMN,WINTER
}

// 定义一个月份
class Month{
    
    

    private Season season;
	
    public Season getSeason() {
    
    
        return season;
    }
    public void setSeason(Season season) {
    
    
        this.season = season;
    }
    
    public Month() {
    
    }
    public Month(Season season) {
    
    
        this.season = season;
    }

    @Override
    public String toString() {
    
    
        return "Month{ season = " + season + '}';
    }

}

// 测试类
public class Test {
    
    
    public static void main(String[] args) {
    
    
        // 定义一个月份类对象
        Month month = new Month();
        // 给他的季节属性赋值
        month.setSeason(Season.AUTUMN);
        System.out.println(month);  // 会打印Month{ season = AUTUMN}
    }
}

The **values()** method in the enumeration class can return an array collection of all enumeration constants;

Season[] values = Season.values();
for (Season s:values) {
     System.out.println(s);  
}

The main function of enumeration :
Define the parameter type as an enumeration class in the parameter list of the method, then when passing parameters, the parameter value can only be selected from the enumeration items of the enumeration class, and there will be no scribbling.

Guess you like

Origin blog.csdn.net/Li_Wendi/article/details/111876874