标签:
1.模拟枚举类型
定义一个类WeekDay:
说明:对于WeekDay中的抽象方法nextDay() 因此类也需要声明为抽象的!当new对象的时候要重写其中的抽象方法!
package cn.itcast.demo; public abstract class WeekDay { private WeekDay(){}//私有构造方法 public final static WeekDay SUN=new WeekDay() { @Override public WeekDay nextDay() { return MON; } }; public final static WeekDay MON=new WeekDay() { @Override public WeekDay nextDay() { return SUN; } }; public final static WeekDay TUES=new WeekDay() { @Override public WeekDay nextDay() { return WED; } }; public final static WeekDay WED=new WeekDay() { @Override public WeekDay nextDay() { return THU; } }; public final static WeekDay THU=new WeekDay() { @Override public WeekDay nextDay() { return FRI; } }; public final static WeekDay FRI=new WeekDay() { @Override public WeekDay nextDay() { return STA; } }; public final static WeekDay STA=new WeekDay() { @Override public WeekDay nextDay() { return SUN; } }; public abstract WeekDay nextDay(); }测试类WeekDayTest
package cn.itcast.demo; public class WeekDayTest { public static void main(String[] args) { WeekDay weekDay=WeekDay.SUN; System.out.println(weekDay.nextDay()); } }打印结果:MON
2.枚举类型简单入门
注:
1)第一行的数据只能是枚举的实例!不能定义成员变量,构造方法
2)枚举类型可以有构造方法,但是只能声明为private,也可以有带有参数的构造方法!
3)要想在枚举的实例中使用带参数的构造方法:语法为 SUN(参数)
4)枚举的静态方法valueOf("str")可以将一个字符串转化为枚举的对象类型
package cn.itcast.demo2; public enum WeekDay{ //下面的SUN(1)是对有参数的构造方法的调用 SUN(1),MON;//第一行只能是枚举类的实例变量 private int day;//不能放在第一行,会报错 private WeekDay(){}//不能放在第一行,会报错 无参数的构造方法,只能声明为private private WeekDay(int day){//有参数的构造方法 this.day=day; } public static void main(String[] args) { WeekDay weekDay=WeekDay.SUN;//这个对象是有参数的构造方法 System.out.println(weekDay.day); WeekDay weekDay2=WeekDay.MON;//无参数的构造方法 System.out.println(WeekDay.valueOf("SUN"));//把字符串转化为对象 } }
运行结果:1 SUN
3.枚举中的抽象类注:
1)枚举中也可以声明抽象方法,但是枚举中的实例常量,必须重写该方法!
package cn.itcast.demo2; public class TrafficLampTest { public static void main(String[] args) { TrafficLamp lamp=TrafficLamp.GREEN; System.out.println(lamp.nextLamp());//实际上调用的是匿名内部类中的已经实现抽象方法的方法 } } enum TrafficLamp{ RED(50) { @Override public TrafficLamp nextLamp() { return GREEN; } },GREEN(20) { @Override public TrafficLamp nextLamp() { return YELLOW; } },YELLOW(10) {//有参数的构造方法 @Override public TrafficLamp nextLamp() { return RED; } }; private TrafficLamp(){}//没有参数的构造方法 private int time;//定义时间 private TrafficLamp(int time){//有参数的构造方法 this.time=time; } public abstract TrafficLamp nextLamp();//定义抽象方法 }运行结果:YELLOW
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/u014010769/article/details/47747489