The usage of enumeration types in Java language is as follows:
Usage 1: constant; public?enum?Color?{?RED,?GREEN,?BLANK,?YELLOW?
}
Usage 2: switch;?enum?Signal?{
GREEN,?YELLOW,?RED
} p>
public?class?TrafficLight?{
Signal?color?=?Signal.RED;
public?void?change()?{
< p>switch?(color)?{case?RED:
color?=?Signal.GREEN;
break;
case?YELLOW:
color?=?Signal.RED;
break;
case?GREEN:
color?= ?Signal.YELLOW;
break;
}
}
}
Usage three: to the list Add a new method to the list; public?enum?Color?{
RED("Red",?1),?GREEN("Green",?2),?BLANK("White",?3 ),?YELLO("yellow",?4);
//?Member variable
private?String?name;
private?int?index ;
//?Construction method
private?Color(String?name,?int?index)?{
this.name?=?name;
this.index?=?index;
}
//?Common method
public?static?String?getName( int?index)?{
for?(Color?c?:?Color.values())?{
if?(c.getIndex()?==?index )?{
return?c.name;
}
}
return?null;
}
//?get?set?method
public?String?getName()?{
return?name;
}
public?void?setName(String?name)?{
this.name?=?name;
}
public?int?getIndex()?{
return?index;
}
public?void?setIndex(int?index)?{
this.index?=?index;
}
}
Usage 4: Override enumeration methods; public?class?Test? {
public?enum?Color?{
RED("Red",?1),?GREEN("Green",?2),?BLANK("White", ?3),?YELLO("Yellow",?4);
//?Member variable
private?String?name;
private?int ?index;
//?Construction method
private?Color(String?name,?int?index)?{
this.name?=? name;
this.index?=?index;
}
//?Override method
@Override
public?String?toString()?{
return?this.index?+?"_"?+?this.name;
}
< p>}public?static?void?main(String[]?args)?{
System.out.println(Color.RED.toString());
p>}
}
Usage 5: Implement interface; public?interface?Behaviour?{
void?print();
String?getInfo();
}
public?enum?Color?implements?Behaviour?{
RED("Red",? 1),?GREEN("green",?2),?BLANK("white",?3),?YELLO("yellow",?4);
//?Member variables p>
private?String?name;
private?int?index;
//?Construction method
private?Color(String?name ,?int?index)?{
this.name?=?name;
this.index?=?index;
}
//?Interface method
@Override
public?String?getInfo()?{
return?this.name;
}
//?Interface method
@Override
public?void?print()?{
System. out.println(this.index?+?":"?+?this.name);
}
}
Usage 6: Use interface organization enumerate. public?interface?Food?{
enum?Coffee?implements?Food?{ BLACK_COFFEE,?DECAF_COFFEE,?LATTE,?CAPPUCCINO
} enum?Dessert?implements?Food?{ FRUIT,?CAKE,?GELATO }
}
The above is the basic usage of enumeration types in Java language.