更多 Java 基础知识方面的文章,请参见文集《Java 基础知识》
Java Enum 枚举
- 枚举类为
final
,不能被继承 - 枚举值默认为
static final
枚举其实就是特殊的常量类,且构造方法被默认强制是私有。
示例:
public class Enum_Test {
public static void main(String[] args) {
Color c = Color.RED;
// 输出 GREEN
System.out.println(Color.valueOf("GREEN"));
// 输出 0
System.out.println(c.ordinal());
}
}
enum Color {
RED, GREEN, BLUE
}
枚举类也可以定义构造函数
参考:https://www.avajava.com/tutorials/lessons/how-do-i-use-the-enum-type-with-a-constructor.html
public class EnumDemo {
public enum Food {
HAMBURGER(7), FRIES(2), HOTDOG(3), ARTICHOKE(4);
Food(int price) {
this.price = price;
}
private final int price;
public int getPrice() {
return price;
}
}
public static void main(String[] args) {
for (Food f : Food.values()) {
System.out.print("Food: " + f + ", " + f.getPrice() + ", ");
switch (f) {
case HAMBURGER:
System.out.println("Tasty");
continue;
case ARTICHOKE:
System.out.println("Delicious");
continue;
default:
System.out.println("OK");
}
}
}
}