热门文章
今天就跟大家聊聊有关Java中enum的用法有哪些,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。
枚举是Java1.5引入的新特性,通过关键字enum来定义枚举类。枚举类是一种特殊类,它和普通类一样可以使用构造器、定义成员变量和方法,也能实现一个或多个接口,但枚举类不能继承其他类.
publicenumWeekDay{SUN,MON,TUE,WED,THT,FRI,SAT}
publicenumWeekDay{SUN,MON,TUE,WED,THT,FRI,SAT}publicclassSelectDay{WeekDayweekday=WeekDay.SUN;publicvoidselect(){switch(weekday){caseSUN:weekday=WeekDay.SUN;break;...}}}
publicenumColor{RED("红色",1),GREEN("绿色",2),BLANK("白色",3),YELLO("黄色",4);//成员变量privateStringname;privateintindex;//构造方法privateColor(Stringname,intindex){this.name=name;this.index=index;}//普通方法publicstaticStringgetName(intindex){for(Colorc:Color.values()){if(c.getIndex()==index){returnc.name;}}returnnull;}//getset方法publicStringgetName(){returnname;}publicvoidsetName(Stringname){this.name=name;}publicintgetIndex(){returnindex;}publicvoidsetIndex(intindex){this.index=index;}}
publicenumColor{RED("红色",1),GREEN("绿色",2),BLANK("白色",3),YELLO("黄色",4);//成员变量privateStringname;privateintindex;//构造方法privateColor(Stringname,intindex){this.name=name;this.index=index;}//覆盖方法@OverridepublicStringtoString(){returnthis.index+"_"+this.name;}}
publicinterfaceBehaviour{voidprint();StringgetInfo();}publicenumColorimplementsBehaviour{RED("红色",1),GREEN("绿色",2),BLANK("白色",3),YELLO("黄色",4);//成员变量privateStringname;privateintindex;//构造方法privateColor(Stringname,intindex){this.name=name;this.index=index;}//接口方法@OverridepublicStringgetInfo(){returnthis.name;}//接口方法@Overridepublicvoidprint(){System.out.println(this.index+":"+this.name);}}
publicinterfaceFood{enumCoffeeimplementsFood{BLACK_COFFEE,DECAF_COFFEE,LATTE,CAPPUCCINO}enumDessertimplementsFood{FRUIT,CAKE,GELATO}}
publicclassTest{publicstaticvoidmain(String[]args){EnumSet<WeekDay>week=EnumSet.noneOf(WeekDay.class);week.add(WeekDay.MON);System.out.println("EnumSet中的元素:"+week);week.remove(WeekDay.MON);System.out.println("EnumSet中的元素:"+week);week.addAll(EnumSet.complementOf(week));System.out.println("EnumSet中的元素:"+week);week.removeAll(EnumSet.range(WeekDay.FRI,WeekDay.SAT));System.out.println("EnumSet中的元素:"+week);}
看完上述内容,你们对Java中enum的用法有哪些有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。