其他分享
首页 > 其他分享> > 枚举的有关知识点

枚举的有关知识点

作者:互联网

什么是枚举,枚举是什么意思,这样说吧,类的对象只有确定的有限个,这样我们就可以称之为枚举,例如:星期;性别;季节.......

当需要定义一组常量的时候,强烈建议使用枚举!!!!!!!!!!!!!!!!

JDK1.5之前,我们需要自定义枚举,就像下面这⬇

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

/**
 *  自定义一个季节枚举类
 */
class Season{
    //2、创建Season的属性,常量处理
    private final String SEASON_NAME;
    private final String SEASON_DESC;


    //1、要保证类的对象的个数是有限的
    //那么我们必须要私有构造方法
    private Season(String SEASON_NAME,String SEASON_DESC){
        this.SEASON_NAME = SEASON_NAME;
        this.SEASON_DESC = SEASON_DESC;
    }

    //3、提供公共的静态的方法给外界获取枚举类的多个对象
    public static final Season SPRING = new Season("春天", "万物复苏");
    public static final Season SUMMER = new Season("夏天", "万物复苏2");
    public static final Season AUTUMN = new Season("秋天", "万物复苏3");
    public static final Season WINTER = new Season("冬天", "万物复苏4");

    //4、提供SEASON_NAME和SEASON_DESC的get方法
    public String getSEASON_NAME() {
        return SEASON_NAME;
    }

    public String getSEASON_DESC() {
        return SEASON_DESC;
    }

    //5、重写toString()

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

但是在JDK1.5之后,我们就可以通过关键字enum定义枚举类了

package com.shujia.java.day27.regulardemos;

/*
    枚举类:
        JDK1.5之前:自定义枚举
        JDK1.5之后:通过关键字enum定义枚举类
 */
public class EnumDemo2 {
    public static void main(String[] args) {
        Season2 spring = Season2.SPRING;
        System.out.println(spring);
        System.out.println(Season2.class.getSuperclass());
    }
}

/**
 *  自定义一个季节枚举类
 */
enum Season2{

    //3、枚举有的有限个对象,对象之间通过逗号连接,最后一个分号结尾
    //枚举相关的放在头部
    SPRING("春天", "万物复苏"),
    SUMMER("夏天", "万物复苏2"),
    AUTUMN("秋天", "万物复苏3"),
    WINTER("冬天", "万物复苏4");

    //2、创建Season2的属性,常量处理
    private final String SEASON_NAME;
    private final String SEASON_DESC;


    //1、要保证类的对象的个数是有限的
    //那么我们必须要私有构造方法
    private Season2(String SEASON_NAME,String SEASON_DESC){
        this.SEASON_NAME = SEASON_NAME;
        this.SEASON_DESC = SEASON_DESC;
    }


    //4、提供SEASON_NAME和SEASON_DESC的get方法
    public String getSEASON_NAME() {
        return SEASON_NAME;
    }

    public String getSEASON_DESC() {
        return SEASON_DESC;
    }

    //5、重写toString()

//    @Override
//    public String toString() {
//        return "Season{" +
//                "SEASON_NAME='" + SEASON_NAME + '\'' +
//                ", SEASON_DESC='" + SEASON_DESC + '\'' +
//                '}';
//    }
}

枚举类可以实现现实接口

1、直接在枚举类实现接口中的抽象方法

2、在每个枚举对象中实现

标签:知识点,NAME,SEASON,有关,String,枚举,Season,DESC
来源: https://blog.csdn.net/weixin_52731998/article/details/122017213