1.使用enum分发:enum实例不是类型,不能将enum实例作为参数的类型,无法重载eval()。使用构造器来初始化每个enum实例。
interface Letter2<T extends Letter2<T>> { SoThat compete(T upLo); } public class Test3 { enum UpLo implements Letter2<UpLo> { Aa(BB, AA, CC), Bb(CC, BB, CC), Cc(AA, AA, BB); private SoThat s1; private SoThat s2; private SoThat s3; UpLo(SoThat s1, SoThat s2, SoThat s3) { this.s1 = s1; this.s2 = s2; this.s3 = s3; } @Override public SoThat compete(UpLo upLo) { switch (upLo) { case Aa: return s1; case Bb: return s2; case Cc: return s3; } return null; } } public static void main(String[] args) { UpLo u1 = UpLo.Aa; UpLo u2 = UpLo.Cc; System.out.println(u1.compete(u2)); } }
2.使用常量相关方法:为enum实例编写方法,为每个enum实例赋予各自不同的行为。要实现常量相关的方法,需要为enum定义一个或多个abstract方法,然后为每个enum实例实现该抽象方法,可覆盖常量相关的方法。
public enum Test4 { SPRING { String getInfo() { return "SPRING"; } }, SUMMER { String getInfo() { return "SUMMER"; } }, AUTUMN { String getInfo() { return "AUTUMN"; } }, WINTER { String getInfo() { return "WINTER"; } }; abstract String getInfo(); public static void main(String args[]) { for (Test4 method : values()) { System.out.println(method.getInfo()); } } }