java枚举小结

  1. 如何定义一个枚举类?

     //定义了4个等级
    enum Level{
    A,B,C,D
    }
  2. 枚举类的实质:

     class Level{
    public static final Level A = new Level();
    public static final Level B = new Level();
    public static final Level C = new Level();
    public static final Level D = new Level();
    }
  3. 枚举类可以定义构造方法,属性,方法

     enum Level{
    A("85~100","优"),
    B("75~84","良"),
    C("60~74","中"),
    D("60以下","差");
    private String score;
    private String ctype;
    private Level(String score,String ctype){ //构造方法必须是私有的
    this.score = score ;
    this.ctype = ctype;
    }
    public String getscore(){
    return this.score;
    }
    public String getctpye(){
    return this.ctype;
    }
    }
    public class Enumation {
    public static void main(String[] args) {
    System.out.println(Level.A.getscore());
    System.out.println(Level.A.getctpye());
    Level[] ls = Level.values();
    }
    }
    //输出结果
    //85~100
    //优
  4. 带抽象方法的枚举类
     enum Level{
    A("85~100"){
    @Override
    public String getctpye() {
    return "优";
    }
    },
    B("75~84") {
    @Override
    public String getctpye() {
    return "良";
    }
    },
    C("60~74") {
    @Override
    public String getctpye() {
    return "中";
    }
    },
    D("60以下") {
    @Override
    public String getctpye() {
    return "差";
    }
    };
    private String score;
    private Level(String score){
    this.score = score ;
    }
    public String getscore(){
    return this.score;
    }
    public abstract String getctpye(); //每个对象都要重写抽象方法 }
  5. 常用方法

     public class Enumation {
    public static void main(String[] args) {
    System.out.println(Level.C.name()); //返回枚举常量的名称
    System.out.println(Level.C.ordinal()); //返回枚举常量的序号(下标从0开始)
    Level[] ls = Level.values(); //遍历枚举类型
    for(Level l :ls){
    System.out.println(l);
    }
    String letter = "B" ;
    //返回带指定名称的指定枚举类型的枚举常量,若letter为非枚举类型会抛异常java.lang.IllegalArgumentException: No enum constant
    Level b = Level.valueOf(letter);
    System.out.println(b.B);
    }
    }
      

    输出:
    C
    2
    A
    B
    C
    D
    B

上一篇:GUID(Globally Unique Identifier)全局唯一标识符


下一篇:Python print "hello world" SyntaxError: invalid syntax