Java 枚举类型(Enum)是一种特殊的类,用于表示固定数量的常量值。枚举类型的主要用途如下:
public enum Weekday {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}
Weekday day = Weekday.MONDAY;
switch (day) {
case SUNDAY:
System.out.println("Sunday");
break;
case MONDAY:
System.out.println("Monday");
break;
// ...
}
public enum Size {
SMALL, MEDIUM, LARGE
}
public Size getBestSize(int width, int height) {
// ...
}
public enum Singleton {
INSTANCE;
private String message;
public void setMessage(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
}
public enum State {
START, RUNNING, PAUSED, STOPPED
}
public class StateMachine {
private State state;
public void setState(State state) {
this.state = state;
}
// ...
}
总之,Java 枚举类型提供了一种简洁、可读性强的方式来表示和处理一组固定的常量值。