如何定义一个枚举类?
1 //定义了4个等级 2 enum Level{ 3 A,B,C,D 4 }
枚举类的实质:
1 class Level{ 2 public static final Level A = new Level(); 3 public static final Level B = new Level(); 4 public static final Level C = new Level(); 5 public static final Level D = new Level(); 6 }
枚举类可以定义构造方法,属性,方法
1 enum Level{ 2 A("85~100","优"), 3 B("75~84","良"), 4 C("60~74","中"), 5 D("60以下","差"); 6 private String score; 7 private String ctype; 8 private Level(String score,String ctype){ //构造方法必须是私有的 9 this.score = score ; 10 this.ctype = ctype; 11 } 12 public String getscore(){ 13 return this.score; 14 } 15 public String getctpye(){ 16 return this.ctype; 17 } 18 } 19 public class Enumation { 20 public static void main(String[] args) { 21 System.out.println(Level.A.getscore()); 22 System.out.println(Level.A.getctpye()); 23 Level[] ls = Level.values(); 24 } 25 } 26 //输出结果 27 //85~100 28 //优
1 enum Level{ 2 A("85~100"){ 3 @Override 4 public String getctpye() { 5 return "优"; 6 } 7 }, 8 B("75~84") { 9 @Override 10 public String getctpye() { 11 return "良"; 12 } 13 }, 14 C("60~74") { 15 @Override 16 public String getctpye() { 17 return "中"; 18 } 19 }, 20 D("60以下") { 21 @Override 22 public String getctpye() { 23 return "差"; 24 } 25 }; 26 private String score; 27 private Level(String score){ 28 this.score = score ; 29 } 30 public String getscore(){ 31 return this.score; 32 } 33 public abstract String getctpye(); //每个对象都要重写抽象方法 34 35 }
常用方法
1 public class Enumation { 2 public static void main(String[] args) { 3 System.out.println(Level.C.name()); //返回枚举常量的名称 4 System.out.println(Level.C.ordinal()); //返回枚举常量的序号(下标从0开始) 5 Level[] ls = Level.values(); //遍历枚举类型 6 for(Level l :ls){ 7 System.out.println(l); 8 } 9 String letter = "B" ; 10 //返回带指定名称的指定枚举类型的枚举常量,若letter为非枚举类型会抛异常java.lang.IllegalArgumentException: No enum constant 11 Level b = Level.valueOf(letter); 12 System.out.println(b.B); 13 } 14 }
输出:
C
2
A
B
C
D
B