美文网首页
枚举--java24(02/17/2016)

枚举--java24(02/17/2016)

作者: Girl_endless | 来源:发表于2016-02-18 17:24 被阅读13次

    如何自定义枚举类
    如何使用enum定义枚举类、枚举类的主要方法
    实现接口的枚举类

    JDK1.5之前需要自定义枚举类
    JDK1.5新增的enum关键字用于定义枚举类
    若枚举只有一个成员,则可以作为一种单例模式的实现方式

    枚举类对象的属性不应允许被改动,所以应该使用private final修饰。同时枚举类用private final修饰的属性应该在构造器中为其赋值。若枚举类显式的定义了带参数的构造器,则在列出枚举值时也必须对应的传入参数。

    package com.atguigu.java1;
    /*
     *  一、枚举类
     * 1.如何自定义枚举类
     */
    
    public class TestSeason {
    
        public static void main(String[] args){
            Season spring = Season.SPRING;
            System.out.println(spring);
            //spring.show();
            System.out.println(spring.getSeasonName());
        }
    
    }
    //枚举类
    class Season{
        //1.提供类的属性,声明为private final
        private final String seasonName;
        private final String seasonDesc;
        //2.声明为final的属性,在构造器中初始化
        private Season(String seasonName, String seasonDesc){
            this.seasonName = seasonName;
            this.seasonDesc = seasonDesc;
        }
        //3.通过公共的方法来调用属性
        public String getSeasonName() {
            return seasonName;
        }
        public String getSeasonDesc() {
            return seasonDesc;
        }
        //4.创建枚举类的对象:将类的对象声明为public static final
        public static final Season SPRING = new Season("spring","春暖花开");
        public static final Season SUMMER = new Season("summer","夏日炎炎");
        public static final Season AUTOMN = new Season("automn","秋高气爽");
        public static final Season WINTER = new Season("winter","白雪皑皑");
        @Override
        public String toString() {
            return "Season [seasonName=" + seasonName + ", seasonDesc="
                    + seasonDesc + "]";
        }
        
    }
    

    相关文章

      网友评论

          本文标题:枚举--java24(02/17/2016)

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