该方法通过字符串获取对应的枚举常量
@Test public void testValueOf() { DirectionEnum east = DirectionEnum.valueOf("EAST"); System.out.println(east.ordinal());// 输出0 } 3.2 继承的方法因为枚举类型继承于 java.lang.Enum, 因此除了该类的私有方法, 其他方法都是可以使用的。
3.2.1 ordinal()该方法返回的是枚举实例的在定义时的顺序, 类似于数组, 第一个实例该方法的返回值为 0。
在基于枚举的复杂数据结构 EnumSet和EnumMap 中会用到该函数。
@Test public void testOrdinal() { System.out.println(DirectionEnum.EAST.ordinal());// 输出 0 System.out.println(DirectionEnum.NORTH.ordinal()); // 输出 2 } 3.2.2 compareTo()该方法时实现的 Comparable 接口的, 其实现如下
public final int compareTo(E o) { Enum<?> other = (Enum<?>)o; Enum<E> self = this; if (self.getClass() != other.getClass() && // optimization self.getDeclaringClass() != other.getDeclaringClass()) throw new ClassCastException(); return self.ordinal - other.ordinal; }首先, 需要枚举类型是同一种类型, 然后比较他们的 ordinal 来得出大于、小于还是等于。
@Test public void testCompareTo() { System.out.println(DirectionEnum.EAST.compareTo(DirectionEnum.EAST) == 0);// true System.out.println(DirectionEnum.WEST.compareTo(DirectionEnum.EAST) > 0); // true System.out.println(DirectionEnum.WEST.compareTo(DirectionEnum.SOUTH) < 0); // true } 3.2.3 name() 和 toString()该两个方法都是返回枚举常量的名称。 但是, name() 方法时 final 类型, 是不能被覆盖的! 而 toString 可以被覆盖。
3.2.4 getDeclaringClass()获取对应枚举类型的 Class 对象
@Test public void testGetDeclaringClass() { System.out.println(DirectionEnum.WEST.getDeclaringClass()); // 输出 class cn.homejim.java.lang.DirectionEnum } 2.3.5 equals判断指定对象与枚举常量是否相同
@Test public void testEquals() { System.out.println(DirectionEnum.WEST.equals(DirectionEnum.EAST)); // false System.out.println(DirectionEnum.WEST.equals(DirectionEnum.WEST)); // true } 4 枚举类型进阶枚举类型通过反编译我们知道, 其实也是一个类(只不过这个类比较特殊, 加了一些限制), 那么, 在类上能做的一些事情对其也是可以做的。 但是, 个别的可能会有限制(方向吧, 编译器会提醒我们的)
4.1 自定义构造函数首先, 定义的构造函数可以是 private, 或不加修饰符
我们给每个方向加上一个角度
public enum DirectionEnum { EAST(0), WEST(180), NORTH(90), SOUTH(270); private int angle; DirectionEnum(int angle) { this.angle = angle; } public int getAngle() { return angle; } }测试
@Test public void testConstructor() { System.out.println(DirectionEnum.WEST.getAngle()); // 180 System.out.println(DirectionEnum.EAST.getAngle()); // 0 } 4.2 添加自定义的方法以上的 getAngle 就是我们添加的自定义的方法
4.2.1 自定义具体方法我们在枚举类型内部加入如下具体方法
protected void move() { System.out.println("You are moving to " + this + " direction"); }测试
@Test public void testConcreteMethod() { DirectionEnum.WEST.move(); DirectionEnum.NORTH.move(); }输出
You are moving to WEST direction You are moving to NORTH direction 4.2.2 在枚举中定义抽象方法在枚举类型中, 也是可以定义 abstract 方法的
我们在DirectinEnum中定义如下的抽象方法
abstract String onDirection();定义完之后, 发现编译器报错了, 说我们需要实现这个方法
按要求实现
测试
@Test public void testAbstractMethod() { System.out.println(DirectionEnum.EAST.onDirection()); System.out.println(DirectionEnum.SOUTH.onDirection()); }输出
EAST direction 1 NORTH direction 333也就是说抽象方法会强制要求每一个枚举常量自己实现该方法。 通过提供不同的实现来达到不同的目的。
4.3 覆盖父类方法