The following code takes a traffic light as an example:
public static void main(String[] args) {
Trafficlight light = Trafficlight.RED;
System.out.println(light.time);
System.out.println(light.nextLigth());
// The ordinal() method returns the order in which the enumeration is declared
System.out.println(light.ordinal());
// The values() method gets an array of all enumeration types
for(Trafficlight light1:light.values()){
System.out.println(light1.name());
}
// The valueOf() method can convert the string into the corresponding enumeration object
System.out.println(light.RED ==light.valueOf("RED"));
}
public enum Trafficlight {
GREEN(30) {
@Override
public Trafficlight nextLigth() {
return RED;
}
},
RED(30) {
@Override
public Trafficlight nextLigth() {
return YELLOW;
}
},
YELLOW(10) {
@Override
public Trafficlight nextLigth() {
return GREEN;
}
};
public abstract Trafficlight nextLigth();
private int time;
//Constructor
private Trafficlight(int time) {
this.time = time;
}
public int getTime(){
return time;
}
}
}
In the code, light is just equivalent to an instance of the parent class. You can use it to get the subclasses of each member variable and call various methods. The valueOf(String) method can convert a string into an enumeration.