美文网首页
Java中的枚举类型

Java中的枚举类型

作者: Ricky_Zuo | 来源:发表于2018-01-06 17:07 被阅读10次

    关于枚举

    枚举类型可以认为是具有固定常量集合的类

    枚举定义在类的内部

    class EnumSeason {
        
        public enum Season {
             SPRING, SUMMER, FALL,WINTER
        }
        
        public static void main(String[] args) {
            for (Season s : Season.values())
                System.out.println(s);
    
        }
    }
    

    输出的自然是

    SPRING
    SUMMER
    FALL
    WINTER

    枚举定义在类的外部

    enum Season { WINTER, SPRING, SUMMER, FALL }  
    public class EnumSeason {
        public static void main(String[] args) {
            Season s=Season.WINTER;  
            System.out.println(s);  
        }
    }
    

    枚举类型赋值

    enum Season {
        SPRING("Spring is warm"), SUMMER("summary is hot"), 
        FALL("Autumn is colorful"),WINTER("winter is cold") ;
    
        public String value;
        private Season(String value) {
            this.value = value;
        }
    }
    
    public class EnumSeason {
        public static void main(String[] args) {
            Season s = Season.WINTER;
            System.out.println(s.value);
           //winter is cold
        }
    }
    

    枚举杂项

    枚举类型可以适配switch case

    enum Season {
        SPRING("Spring is warm"), SUMMER("Summary is hot"), 
        FALL("Autumn is colorful"),WINTER("Winter is cold") ;
    
        public String value;
        private Season(String value) {
            this.value = value;
        }
    }
    
    public class EnumSeason {
        public static void main(String[] args) {
            Season season = Season.WINTER;
            switch (season) {
            case SPRING:
                System.out.println("SPRING:" + season.value);
                break;
            case SUMMER:
                System.out.println("SUMMER:" + season.value);
                break;
            case FALL:
                System.out.println("FALL:" + season.value);
                break;
            case WINTER:
                System.out.println("WINTER:" + season.value);
                break;
            default:
                break;
            }
        }
    }
    

    枚举类型的基础认知

    • 父类是java.lang.Enum
    • 非抽象枚举类是final的
    • 构造器必需是私有的
    • 枚举的类型必需在枚举一开始就列出
    • 枚举类可以是抽象的,可以实现接口

    先列出这些吧,以上是我在学习这个知识点的时候从书籍和网络上看到的知识的一些小结吧~~

    相关文章

      网友评论

          本文标题:Java中的枚举类型

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