定义接口:
public interface myinterface { public abstract Direction changeDirection(boolean clockwise); }
enum枚举了四个实例,要重写接口中的抽象方法。
情况一:若在main方法中不通过实例调用重写的方法,方法是在enum中给所有实例使用的,直接在enum中重写方法。
情况二:若要在main方法中通过枚举的实例调用方法,需要在实例里面重写方法。
public enum Direction implements myinterface{ North{ @Override public Direction changeDirection(boolean clockwise) { if(clockwise==true){ return Direction.East; }else{ return Direction.West; } } },East{ @Override public Direction changeDirection(boolean clockwise) { if(clockwise==true){ return Direction.South; }else{ return Direction.North; } } },South{ @Override public Direction changeDirection(boolean clockwise) { if(clockwise==true){ return Direction.West; }else{ return Direction.East; } } },West{ @Override public Direction changeDirection(boolean clockwise) { if(clockwise==true){ return Direction.North; }else{ return Direction.South; } } }; }
main函数:
public class EnumQuestion { public static void main(String[] args) { Direction.values(); for(Direction d : Direction.values()){ System.out.println("Clockwise of "+d+": "+d.changeDirection(true)); System.out.println("Anti-clockwise of"+d+": "+d.changeDirection(false)+"\n"); } } } 在实例里面重写方法的话,main函数中遍历的d就相当于调用每一个实例,并且可以使用块内部的方法。