1、定义一个enum public enum Grade { A, B, C, D, F, INCOMPLETE }; 2、使用一个enum private Grade grade; public void assignGrade(Grade grade) { public Grade getGrade() { public void testGradeAssignment(PrintStream out) throws IOException { 3、类内声明Enum public class Downloader { public enum DownloadStatus { INITIALIZING, IN_PROGRESS, COMPLETE }; // Class body } PS.Enum默认是static的,就像interface默认是abstract的一样。 4、遍历Enum 重要是values()这个方法,它返回该类型所有可能取值的集合。 public void listGradeValues(PrintStream out) throws IOException { // for loop // for/in loop 5、Enum对switch的支持 public void testSwitchStatement(PrintStream out) throws IOException { switch (student1.getGrade()) { 6、EnumMap的使用 public enum AntStatus { public class AntStatusTester { public AntStatusTester() { } public void testEnumMap(PrintStream out) throws IOException { // Initialize the map // Iterate and print messages public static void main(String[] args) { tester.testEnumMap(System.out); 7、Enum中添加method public enum xxx{ xxx(){ }//构造函数 public int getXxx(){ }//接口 } |
例一:
package com.test4; public enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY }
package com.test4; public class EnumTest { Day day; public EnumTest(Day day) { this.day = day; } public void tellItLikeItIs() { switch (day) { case MONDAY: System.out.println("Mondays are bad."); break; case FRIDAY: System.out.println("Fridays are better."); break; case SATURDAY: case SUNDAY: System.out.println("Weekends are best."); break; default: System.out.println("Midweek days are so-so."); break; } } public static void main(String[] args) { EnumTest firstDay = new EnumTest(Day.MONDAY); firstDay.tellItLikeItIs(); EnumTest thirdDay = new EnumTest(Day.WEDNESDAY); thirdDay.tellItLikeItIs(); EnumTest fifthDay = new EnumTest(Day.FRIDAY); fifthDay.tellItLikeItIs(); EnumTest sixthDay = new EnumTest(Day.SATURDAY); sixthDay.tellItLikeItIs(); EnumTest seventhDay = new EnumTest(Day.SUNDAY); seventhDay.tellItLikeItIs(); } }
结果:
Mondays are bad.
Midweek days are so-so.
Fridays are better.
Weekends are best.
Weekends are best.