枚举类型是那些字段由一组固定常量组成的类型。常见的例子有:东南西北四个方向,星期几等。java
全部枚举类型都隐式继承java.lang.Enum类型,由于java不支持多重继承,因此枚举不能继承其余任何类。this
java对枚举的支持是语言级的支持,switch-case结构无需加枚举名做为前缀。spa
多个枚举常量之间以逗号隔开,枚举常量列表最后能够以分号结束,若是有成员方法或成员变量,必须以分号结束。code
枚举类型能够有成员方法和成员变量。若是有成员方法和成员变量,枚举常量列表要放在枚举体最开始,以分号结尾。blog
枚举类型的构造器必须是包级私有或者私有,构造器会自动建立枚举类型体开端定义的枚举常量。继承
1 enum Day { 2 SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY 3 } 4 public class EnumTest { 5 static void tell(Day data) { 6 switch (data) { 7 case MONDAY : 8 System.out.println(1); 9 break; 10 case SUNDAY : 11 System.out.println(0); 12 default : 13 break; 14 } 15 } 16 public static void main(String[] args) { 17 Day x = Day.MONDAY; 18 tell(x); 19 for (Day i : Day.values()) { 20 System.out.println(i); 21 } 22 } 23 }
1 enum Planet { 2 MERCURY(303E23, 2.4397E6), VENUS(4.869E24, 6.0518E6), EARTH(5.97E24, 3 6.378E6); 4 final double mass; 5 double radius; 6 private Planet(double mass, double radius) { 7 this.mass = mass; 8 this.radius = radius; 9 } 10 final double G = 6.67E-11; 11 double getGravity() { 12 return G * mass / (radius * radius); 13 } 14 } 15 class EnumTest { 16 final int x; 17 public EnumTest() { 18 x = 3; 19 } 20 public static void main(String[] args) { 21 for (Planet i : Planet.values()) { 22 System.out.printf(i + "\t" + i.mass + "\t" + i.radius + "\t" 23 + i.getGravity()+"\n"); 24 } 25 } 26 }