Java中的Enum枚举类型总结
废话不多说,直接上代码,该例子来源于:http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html
public enum Planet { MERCURY (3.303e+23, 2.4397e6), VENUS (4.869e+24, 6.0518e6), EARTH (5.976e+24, 6.37814e6), MARS (6.421e+23, 3.3972e6), JUPITER (1.9e+27, 7.1492e7), SATURN (5.688e+26, 6.0268e7), URANUS (8.686e+25, 2.5559e7), NEPTUNE (1.024e+26, 2.4746e7); private final double mass; // in kilograms private final double radius; // in meters /*1、构造器:可以给常量赋予更多的属性,必须是private,可以保证使用者不能私自new一个Enum出来*/ Planet(double mass, double radius) { this.mass = mass; this.radius = radius; } private double mass() { return mass; } private double radius() { return radius; } // universal gravitational constant (m3 kg-1 s-2) public static final double G = 6.67300E-11; //2、可以内定义丰富的方法*/ double surfaceGravity() { return G * mass / (radius * radius); } public static void main(String[] args) { /*3、方法values()返回所有的枚举类型的数组 *4、方法ordinal()返回在枚举列表中的默认位置(从0开始) *5、针对Enum的toString()方面直接输出枚举名称 *6、方法name()返回枚举名称 */ for (Planet p : Planet.values()) System.out.println("Name:"+p.name()+" Position:"+p.ordinal()+" P:"+p); /*7、方法valueOf可以从Stirng名称返回Enum类型的枚举类型*/ System.out.println(Planet.valueOf("NEPTUNE").name());
/*8、再来一个使用数组的例子*/
System.out.println(Planet.values()[2].name()); } }
输出结果如下:
Name:MERCURY Position:0 P:MERCURY Name:VENUS Position:1 P:VENUS Name:EARTH Position:2 P:EARTH Name:MARS Position:3 P:MARS Name:JUPITER Position:4 P:JUPITER Name:SATURN Position:5 P:SATURN Name:URANUS Position:6 P:URANUS Name:NEPTUNE Position:7 P:NEPTUNE NEPTUNE EARTH
下面用javap命令反编译Planet.class
/*1、Enum本身是一个继承自java.lang.Enum的类
2、枚举成员都是public static final类型
3、可以看到values、valueOf的方法声明
*/
public final class javalearn.Planet extends java.lang.Enum<javalearn.Planet> { public static final javalearn.Planet MERCURY; public static final javalearn.Planet VENUS; public static final javalearn.Planet EARTH; public static final javalearn.Planet MARS; public static final javalearn.Planet JUPITER; public static final javalearn.Planet SATURN; public static final javalearn.Planet URANUS; public static final javalearn.Planet NEPTUNE; public static final double G; static {}; double surfaceGravity(); public static void main(java.lang.String[]); public static javalearn.Planet[] values(); public static javalearn.Planet valueOf(java.lang.String); }