Examples of using Java enumerations
- 2020-04-01 02:36:21
- OfStack
public class test {
public static void main(String[] args) {
WeekDay w = WeekDay.MON;
System.out.println(w);//I'm going to call the tostring method myself
System.out.println(w.ordinal());//Printing is enumerating the number of objects in the list
System.out.println(WeekDay.values().length);//How many enumeration objects are there
}
public enum WeekDay{
SAT,MON,TUE,WED,THU,FRI,SAT,
private WeekDay(){
System.out.println("11");
}
private WeekDay(int a){
System.out.println("a");
}
}
}
First, a simple enumeration class, the WeekDay , is defined above.
In this class sat, mon.. And so are actually objects of the weekday class
Note:
Enumeration classes also have constructors, which must be private.
The following code should be able to understand the use of enumeration types, in conjunction with the inner class to understand
public enum TrefficLamp{
RED(30){//The red light object calls the constructor with an int parameter,
public TrefficLamp nextLamp(){
return GREEN;
}
},
GREEN(20){
public TrefficLamp nextLamp(){
return YELLOW;
}
},
YELLOW(2){
public TrefficLamp nextLamp(){
return RED;
}
};
public abstract TrefficLamp nextLamp();
private int time;
private TrefficLamp(int time){
this.time = time;
};
}