标签:
enum关键字用于定义枚举类,若枚举只有一个成员, 则可以作为一种单例模式的实现方式。
/*枚举类的自定义方式*/ public class TestSeason { public static void main(String[] args){ Season spring=Season.SPRING; System.out.println(spring); System.out.println(spring.getSeasonName()); } } //枚举类 class Season{ //1.提供类的属性,声明为private final private final String seasonName; private final String seasonDesc; //2.声明为final的属性,在构造器中初始化 private Season(String seasonName,String seasonDesc){ this.seasonName=seasonName; this.seasonDesc=seasonDesc; } public static final Season SPRING=new Season("spring","春暖花开"); public static final Season SUMMER=new Season("summer","夏日炎炎"); public static final Season AUTOMN=new Season("automn","秋高气爽"); public static final Season WINTER=new Season("winter","白雪皑皑"); //通过公共的方法来调用属性 public String getSeasonName() { return seasonName; } public String getSeasonDesc() { return seasonDesc; } @Override public String toString() { return "Season [seasonName=" + seasonName + ", seasonDesc=" + seasonDesc + "]"; } }
/* * 一.枚举类 * 1.如何自定义枚举类 * 2.如何使用enum关键字定义枚举类 * 常用的方法;values(),valueOf(String str) * 如何使枚举类实现接口:可以让不同的枚举类的对象调用被重写的抽象方法,执行的效果不同(相当于每个对象重写抽象方法) * */ public class TestSeason1{ public static void main(String[] args){ SeasonEnum spring=SeasonEnum.SPRING; System.out.println(spring); System.out.println(spring.getSeasonName()); //1.values方法可以返回枚举类型的对象数组,可以方便遍历所有的枚举值 SeasonEnum[] seasons=SeasonEnum.values(); for(int i=0;i<seasons.length;i++){ System.out.println(seasons[i]); } //2.valueOf方法可以把一个字符串转为对应的枚举类对象,要求字符串必须是枚举类对象的“名字” String str="WINTER"; SeasonEnum sea=SeasonEnum.valueOf(str); System.out.println(sea); //不同的枚举类对象调用重写的show方法得到不同的效果 spring.show(); sea.show(); } } //接口 interface Info{ public void show(); } //实现接口的枚举类 enum SeasonEnum implements Info{ //必须在枚举类的第一行声明枚举类对象 SPRING("spring","春暖花开"){ public void show(){ System.out.println("春天在哪里"); } }, SUMMER("summer","夏日炎炎"){ public void show(){ System.out.println("生如夏花"); } }, AUTOMN("autumn","秋高气爽"){ public void show(){ System.out.println("金色的秋天"); } }, WINTER("winter","白雪皑皑"){ public void show(){ System.out.println("冬天里的一把火"); } }; private final String seasonName; private final String seasonDesc; private SeasonEnum(String seasonName, String seasonDesc) { this.seasonName = seasonName; this.seasonDesc = seasonDesc; } public String getSeasonName() { return seasonName; } public String getSeasonDesc() { return seasonDesc; } }
标签:
原文地址:http://www.cnblogs.com/xujiming/p/4638494.html