美文网首页
JDK5-枚举

JDK5-枚举

作者: Josaber | 来源:发表于2017-01-09 22:28 被阅读0次

    使用普通类模拟枚举

    public class Weekday {
        private Weekday() {} // 私有化
        
        public static final Weekday MONDAY = new Weekday();  // 每个枚举都是一个对象
        public static final Weekday TUESDAY = new Weekday();
    
        public String toString() {
            if(this == MONDAY)
                return "Monday";
            else if(...) ...
        }
    }
    

    使用抽象类模拟枚举

    public abstract class Weekday {
        private Weekday() {}
    
        public final static Weekday MONDAY = new Weekday() {
            public Weekday nextDay() {
                return TUESDAY;
            }
        };
    
        public final static Weekday TUESDAY = new Weekday() {
            public Weekday nextDay() {
                return WEDNESDAY;
            }
        };
    
        ...
    
        public abstract Weekday nextDay();
    }
    

    使用抽象类模拟可以免除toString()写大量的if-else语句,不需要对每个对象进行判断,只需要有具体实现类完成即可

    枚举类

    public enum Weekday {
      SUN, MON, TUE, WED, THU, FRI, SAT
    }
    

    普通的枚举类末尾不需要写分号

    带构造参数枚举

    public enum Weekday {    
        SUN(5), MON(), TUE(7), WED(), THU(9), FRI, SAT;    // 必须第一行,且以分号结尾
    
        private Weekday() {}
        private Weekday(int number) {
            System.out.println(number);
        }
    }
    

    枚举中每个变量都是static final的

    带抽象函数的枚举

    public enum Weekday {    // enum不用abstract修饰
        SUN(5) {
            public Weekday nextDay() {
                return MON;
            }
        }, 
        MON() {
            public Weekday nextDay() {
                return TUE;
            }
        }, 
        TUE() {
            public Weekday nextDay() {
                return WED;
            }
        }, 
        WED() {
            public Weekday nextDay() {
                return THU;
            }
        }, 
        THU() {
            public Weekday nextDay() {
                return FRI;
            }
        }, 
        FRI() {
            public Weekday nextDay() {
                return SAT;
            }
        }, 
        SAT() {
            public Weekday nextDay() {
                return SUN;
            }
        };
    
        private Weekday() {}
        private Weekday(int number) {
            System.out.println(number);
        }
    
        public abstract Weekday nextDay();
    }
    

    枚举类中的方法

    toString() - String
    name() - String
    ordinal() - int
    valueOf(String name) - Weekday
    values() - Weekday[]
    ... ...

    相关文章

      网友评论

          本文标题:JDK5-枚举

          本文链接:https://www.haomeiwen.com/subject/rlohbttx.html