枚举类 解

package ZHANG.API; public class TestEnum { public enum Action { Turn_left, Turn_right, Shoot } /** * @param args */ public static void main(String[] args) { doAction(Action.Shoot); } public static void doAction(Action action){ switch(action){ case Turn_left: System.out.println("向左转"); break; case Turn_right: System.out.println("向右转"); break; case Shoot: System.out.println("射击"); break; } } }

 

用普通的类实现Enum的原理:   模拟枚举

WeekDay.java

package ZHANG.API; public abstract class WeekDay { private WeekDay(){} /*public final static WeekDay SUN = new WeekDay(); public final static WeekDay MON = new WeekDay(); public final static WeekDay THR = new WeekDay();*/ //由子类分别去完成,不由父类去完成 public final static WeekDay SUN = new WeekDay(){ @Override public WeekDay nextDay() { // TODO Auto-generated method stub return null; } }; public final static WeekDay MON = new WeekDay(){ @Override public WeekDay nextDay() { // TODO Auto-generated method stub return null; }}; public final static WeekDay THR = new WeekDay(){ @Override public WeekDay nextDay() { // TODO Auto-generated method stub return null; }}; public abstract WeekDay nextDay(); //抽象方法,类就必须声明为抽象内 /* public WeekDay nextDay(){ if(this == SUN){ return MON; }else{ return SUN; } }*/ public String toString(){ return this == SUN ? "SUN":"MON"; } }

EnumTest.java

package ZHANG.API; public class EnumTest { public static void main(String[] args) { WeekDay weekDay =WeekDay.SUN; System.out.println(weekDay.nextDay()); } }

 

以下枚举入门:

枚举的构造函数必须是私有的

public class EnumTest { public static void main(String[] args) { WeekDay weekDay =WeekDay.SUN; System.out.println(weekDay.nextDay()); //演示枚举的方法 WeekDay1 weekDay1 = WeekDay1.FRI; System.out.println(weekDay1); System.out.println(weekDay1.name()); System.out.println(weekDay1.ordinal()); System.out.println(WeekDay1.valueOf("SUN").toString()); //调用类的静态方法 System.out.println(WeekDay1.values().length); //返回枚举的数组 } public enum WeekDay1{ SUN(1),MON,THE,WED,THI,FRI,SAT; private WeekDay1(){ System.out.println("first"); } private WeekDay1(int day){ System.out.println("second"); } }}

在以上代码中增加一个枚举

public enum TrafficLamp{ //抽象,实例对象必须去完成子类的抽象方法,,,new子类的实例对象,并且调用父类的构造方法 RED(30){ public TrafficLamp nextLamp(){ return GREEN; } }, GREEN(35){ public TrafficLamp nextLamp(){ return YELLOW; } }, YELLOW(10){ public TrafficLamp nextLamp(){ return RED; } }; public abstract TrafficLamp nextLamp(); //私有成员变量 ,再增加一个构造方法 private int time; private TrafficLamp(int time){ this.time = time; } }

 如果枚举只有一个成员时,就可以作为一种单例的实现方式

你可能感兴趣的:(枚举类 解)