JDK5之前的定义方式

使用自定义类实现枚举

package com.zhou.study;

public class SeasonTest {

    public static void main(String[] args) {
        Season spring = Season.spring;
        System.out.println(spring);
    }
}

class Season {
    //定义每个枚举的字段属性   private final修饰
    private final String seasonName;
    private final String seasonDesc;

    //私有化构造器  private    使此类不能被外部new
    private Season(String seasonName, String seasonDesc) {
        this.seasonName = seasonName;
        this.seasonDesc = seasonDesc;
    }

    //定义所有可能的枚举   public static final修饰

    public static final Season spring = new Season("春天","春暖花开");
    public static final Season summer = new Season("夏天","炽热难耐");
    public static final Season autumn = new Season("秋天","天高气爽");
    public static final Season winter = new Season("冬天","寒风凛凛");

//    toString方法,按照情况来


    @Override
    public String toString() {
        return "Season{" +
                "seasonName='" + seasonName + '\'' +
                ", seasonDesc='" + seasonDesc + '\'' +
                '}';
    }
}

JDK5增加的新特性:enum关键字定义枚举类

其父类不是Object,而是java.lang.Enum

enum Season {
    //定义所有可能的枚举   默认public static final修饰   不可以显示的添加

    spring ("春天","春暖花开"),
    summer("夏天","炽热难耐"),
    autumn("秋天","天高气爽"),
    winter("冬天","寒风凛凛");


    //定义每个枚举的字段属性   private final修饰
    private final String seasonName;
    private final String seasonDesc;

    //私有化构造器  private
    private Season(String seasonName, String seasonDesc) {
        this.seasonName = seasonName;
        this.seasonDesc = seasonDesc;
    }

    public String getSeasonName() {
        return seasonName;
    }

    public String getSeasonDesc() {
        return seasonDesc;
    }
}

Enum类的方法

image-20211014110355597

常用方法

image-20211014110421436

枚举类实现接口

先定义一个接口

interface Info {
    void show();
}

情况一:统一实现方法

enum Season implements Info{
    //定义所有可能的枚举   public static final修饰

    spring("春天", "春暖花开"),
    summer("夏天", "炽热难耐"),
    autumn("秋天", "天高气爽"),
    winter("冬天", "寒风凛凛");

    .....省略

    @Override
    public void show() {
        System.out.println("这是一个季节");
    }
}

这是不管是调用哪个季节,输出的都是 这是一个季节.

情况二:分开实现方法

enum Season implements Info{
    //定义所有可能的枚举   public static final修饰

    spring("春天", "春暖花开"){
        @Override
        public void show() {
            System.out.println("这是春天");
        }
    },
    summer("夏天", "炽热难耐") {
        @Override
        public void show() {
            System.out.println("这是夏天");
        }
    },
    autumn("秋天", "天高气爽") {
        @Override
        public void show() {
            System.out.println("这是秋天");
        }
    },
    winter("冬天", "寒风凛凛") {
        @Override
        public void show() {
            System.out.println("这是冬天");
        }
    };

    ......省略

}

此时调用哪个季节的show都会显示对应的方法

最后修改:2021 年 10 月 14 日 04 : 18 PM