zno2

enum

https://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.9

The body of an enum declaration may contain enum constants. An enum constant defines an instance of the enum type.

格式:

[EnumConstantList] [,] [; {ClassBodyDeclaration}]

 语法:

https://docs.oracle.com/javase/specs/jls/se8/html/jls-2.html

The syntax {x} denotes zero or more occurrences of x.

The syntax [x] denotes zero or one occurrences of x.

 

 

// 简单的枚举
enum SimpleEnum {
    RED, YELLOW, GREEN
}

// 复杂的枚举
enum ComplexEnum {
    RED(255, 0, 0), YELLOW(255, 255, 0), GREEN(0, 255, 0);

    private final int r;
    private final int g;
    private final int b;

    ComplexEnum(int r, int g, int b) {
        this.r = r;
        this.g = g;
        this.b = b;
    }

    public int getR() {
        return r;
    }

    public int getG() {
        return g;
    }

    public int getB() {
        return b;
    }

}

 

测试:

    public static void main(String[] args) {
        
        System.out.println(SimpleEnum.GREEN);
        System.out.println();
        System.out.println(ComplexEnum.GREEN);
        System.out.println(ComplexEnum.GREEN.getR());
        System.out.println(ComplexEnum.GREEN.getG());
        System.out.println(ComplexEnum.GREEN.getB());
    }

 

运行结果:

GREEN

GREEN
0
255
0

 

看着就像静态变量,如下是一个小测试:

enum EnumTest {
    A, B, C;
}
E:\>javac EnumTest.java

E:\>javap EnumTest.class
Compiled from "EnumTest.java"
final class EnumTest extends java.lang.Enum<EnumTest> {
  public static final EnumTest A;
  public static final EnumTest B;
  public static final EnumTest C;
  public static EnumTest[] values();
  public static EnumTest valueOf(java.lang.String);
  static {};
}

 

静态变量 (代码按照一定规则生成,逗号分隔简单明了;剩余部分和普通类基本一致 )

静态块

实例变量

实例块

构造函数

。。。

 

posted on 2019-01-21 21:30  zno2  阅读(207)  评论(0编辑  收藏  举报

导航