标签:style blog ar color os sp java strong on
为什么要用枚举?3.可以有若干个公有方法或抽象方法,而采用抽象方法定义的nextDay就将大量的if..else变换成一个一个独立的类
class WeekDay { private WeekDay(){} public final static WeekDay SUN = new WeekDay(); public final static WeekDay MON = new WeekDay(); public WeekDay nextDay(){ return (this==SUN)?MON:SUN; } public String toString(){ return (this==MON)?"MON":"SUN"; } } public class EnumDemo { public static void main(String[] args) { System.out.println(WeekDay.SUN.nextDay()); } }
也可以是将方法定义为抽象的,每个固定的WeekDay对象的子类去复写的
在一个类中编写完各个枚举类和测试调用类,那么就可以将枚举类定义成调用类的内部类
public abstract class WeekDay { private WeekDay(){} public final static WeekDay SUN = new WeekDay(){ public WeekDay nextDay() { return MON; }; }; public final static WeekDay MON = new WeekDay(){//匿名内部类,子类来写nextDay方法 public WeekDay nextDay() { return SUN; }; }; public abstract WeekDay nextDay(); public String toString(){ return (this==MON)?"MON":"SUN"; } }
class Demo{}
new Demo(){} ->new 一个Demo的子类,{}中是子类的代码,这个表示,子类调用的是父类的无参的构造方法
new Demo(20){} ->new子类的实例对象,调用父类的有参的构造方法
枚举的基本应用:
定义一个Week的枚举
枚举是一种特殊的类,其中的每个元素都是该类的一个实例对象,例如可以用WeekDay.SUN.getClass().getName();
public class EnumDemo { public static void main(String[] args) { System.out.println(WeekDay.SUN.nextDay()); Week w = Week.SUN; System.out.println(w); System.out.println(w.name()); System.out.println(w.ordinal());//排第几 System.out.println(w.getClass()); System.out.println(Week.valueOf("SUN"));//将字符串变换成对应的枚举元素 System.out.println(Week.values().length);//将枚举中的每一个元素,都装进数组 } public enum Week{//定义一个枚举类 SUN,MON; } }
public enum Week{//定义一个枚举类 SUN,MON;//所有的东西都必须放在枚举值列表下面 private Week(){System.out.println("WU");};//枚举类的构造方法必须是private private Week(int i){System.out.println("I");}; }
public enum Week{ SUN(5),MON(); private Week(){System.out.println("WU");}; private Week(int i){System.out.println("I");}; }
public class EnumDemo { public static void main(String[] args) { System.out.println(Month.March.nextMonth()); } public enum Month{ //January,February,March,April; January(31){ public Month nextMonth() { return February; } },February(28) { public Month nextMonth() { return March; } },March(30) { public Month nextMonth() { return April; } },April(31) { public Month nextMonth() { return January; } }; public abstract Month nextMonth();//抽象方法,返回类型是自己类型 private int time ; private Month(int time){ this.time = time ;} public String toString(){ if(this==January)return "January"; else if(this==February) return "February"; else if(this==March) return "March"; else return "April"; } } }
标签:style blog ar color os sp java strong on
原文地址:http://blog.csdn.net/wjw0130/article/details/41960917