Java enumeration examples
We have learned enumeration when learning programming languages. Now let's take a look at the usage of enumeration in java.
The Code is as follows:
Public class test {
Public static void main (String [] args ){
WeekDay w = WeekDay. MON;
System. out. println (w); // you can call the tostring method.
System. out. println (w. ordinal (); // print the objects in the enumeration list.
System. out. println (WeekDay. values (). length); // The total number of enumerated objects.
}
Public enum WeekDay {
SAT, MON, TUE, WED, THU, FRI, SAT,
Private WeekDay (){
System. out. println ("11 ");
}
Private WeekDay (int ){
System. out. println ("");
}
}
}
First, we define a simple enumeration class WeekDay.
Sat, mon... and so on in this class are actually weekday class objects.
Note:
Enumeration classes also have constructor methods, which must be private;
The following code can be used to understand the usage of enumeration types. It should be understood in combination with internal classes.
The Code is as follows:
Public enum TrefficLamp {
RED (30) {// The construction method for calling the parameter of the RED light object to be int type,
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;
};
}