Java 基础:枚举

枚举的写法

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 的
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章