java中的枚举类型

枚举类型是那些字段由一组固定常量组成的类型。常见的例子有:东南西北四个方向,星期几等。

所有枚举类型都隐式继承java.lang.Enum类型,因为java不支持多重继承,所以枚举不能继承其他任何类。

java对枚举的支持是语言级的支持,switch-case结构无需加枚举名作为前缀。

多个枚举常量之间以逗号隔开,枚举常量列表最后可以以分号结束,如果有成员方法或成员变量,必须以分号结束。

枚举类型可以有成员方法和成员变量。如果有成员方法和成员变量,枚举常量列表要放在枚举体最开始,以分号结尾。

枚举类型的构造器必须是包级私有或者私有,构造器会自动创建枚举类型体开端定义的枚举常量。

 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 + "	" + i.mass + "	" + i.radius + "	"
23                     + i.getGravity()+"
");
24         }
25     }
26 }
原文地址:https://www.cnblogs.com/weiyinfu/p/5336363.html