枚舉的寫法
enum Shape {
Circle,
Rectangle,
Triangele
}
實際生成的類
// 反編譯 Shape.class
final class Shape extends Enum {
// 編譯器爲我們添加的靜態的 values() 方法
public static Shape[] values() {
return (Shape[]) $VALUES.clone();
}
// 編譯器爲我們添加的靜態的 valueOf() 方法,注意間接調用了 Enum 類的 valueOf 方法
public static Shape valueOf(String s) {
return (Shape) Enum.valueOf(com / gdeer / Shape, s);
}
// 私有構造函數
private Shape(String s, int i) {
super(s, i);
}
// 前面定義的 3 種枚舉實例
public static final Shape Circle;
public static final Shape Rectangle;
public static final Shape Triangle;
private static final Shape $VALUES[];
static {
//實例化枚舉實例
Circle = new Shape("Circle", 0);
Rectangle = new Shape("Rectangle", 1);
Triangle = new Shape("Triangle", 2);
$VALUES = (new Shape[]{
Circle, Rectangle, Triangle
});
}
}
注意點:
- 枚舉類是 final 的,即無法被繼承
- 構造函數是私有的,只能在當前類中生成對象
枚舉的用法
public class EnumDemo {
public static void main(String[] args) {
Shape s = Shape.Circle;
System.out.println(Arrays.toString(Shape.values()));
System.out.println(Shape.valueOf("Circle"));
System.out.println(s.name());
System.out.println(s.ordinal());
}
}
輸出:
[Circle, Rectangle, Triangle]
Circle
Circle
0
枚舉的自定義屬性、方法
enum Shape {
Circle(1),
Rectangle(4),
Triangle(3);
private int edgeCount;
Shape(int count) {
edgeCount = count;
}
public int getEdgeCount() {
return edgeCount;
}
}
注意點:
- 構造函數無法寫成 public,因爲實際生成的類的構造函數是 private 的