Java6学习笔记53——枚举类型

注意:枚举类型也是类

java.lang.Enum <E extends Enum <E>>

使用enum定义。

类如:

public class EnumDemo2 {
enum Edge {
TOP, BOTTOM, LEFT, RIGHT
};
public static void main(String arg[]) {
Edge edge = Edge.LEFT;

int i = edge.ordinal();
System.out.println("The value of i: " + i);
System.out.println(edge);

String str = "";
switch(edge) {
/* case Edge.TOP: This is wrong*/
case TOP: str = "The top edge"; break;
case BOTTOM: str = "The bottom edge"; break;
case LEFT: str = "The left edge"; break;
case RIGHT: str = "The right edge"; break;
}
System.out.println(str);
}
}


这就解决了switch不能对字符串进行的缺点了。

更复杂的应用:

public enum Day {
MONDAY (8,true),
TUESDAY (8,true),
WEDNESDAY (8,true),
THURSDAY (8,true),
FRIDAY (8,true),
SATURDAY (4,false),
SUNDAY (0,false);

private int hours;
private boolean weekday;
Day(int workHours,boolean weekdayFlag) {
hours = workHours;
weekday = weekdayFlag;
}
public int getHours() {
return(hours);
}
public boolean isWeekday() {
return(weekday);
}
public static void main(String arg[]) {
Day day;

day = Day.TUESDAY;
showDay(day);

day = Day.SATURDAY;
showDay(day);
}
private static void showDay(Day d) {
if(d.isWeekday()) {
System.out.println(d + " is a weekday and has " +
d.getHours() + " working hours.");
} else {
System.out.println(d + " is not a weekday and has " +
d.getHours() + " working hours.");
}
}
}

你可能感兴趣的:(java)