Java枚举-9

目录

枚举引出

自定义枚举


枚举引出

Java枚举-9_第1张图片

自定义枚举

package com.edu.eum;

public class eum01 {
    public static void main(String[] args) {
        //使用
        Season spring = new Season("春天","温暖");
        Season winter = new Season("冬天","寒冷");

    }

}
//自定义枚举
/*
1、构造器私钥化,目的防止直接new对象出来
2、去掉set相关方法,防止属性被修改
3、在Season内部创建固定对象
4、优化可以再加入一个final
5、枚举对象名要全部大写

 */
class Season{
    private String name;
    private String desc;
    //定义固定对象
    public static final Season spring = new Season("春天","温暖");
    public static  Season winter = new Season("冬天","温暖");

    private Season(String name, String desc) {
        this.name = name;
        this.desc = desc;
    }

    public String getName() {
        return name;
    }

    public String getDesc() {
        return desc;
    }

}
//1、使用关键字enum
//2、直接SPRINT("春天","温暖"),有多个用,间隔
//3、常量对象要写在最前面
enum Season02{
    SPRINT("春天","温暖"),
    WINTER("春天","温暖");
    private String name;
    private String desc;

    private Season02(String name, String desc) {
        this.name = name;
        this.desc = desc;
    }

    public String getName() {
        return name;
    }

    public String getDesc() {
        return desc;
    }

}

Java枚举-9_第2张图片Java枚举-9_第3张图片

Java枚举-9_第4张图片

Enum成员方法

package com.edu.eum;

public class enum04 {
    public static void main(String[] args) {
        Season02 spring = Season02.SPRING;
        //输出枚举对象的名称
        System.out.println(spring.name());
        //输出枚举对象的次序
        System.out.println(spring.ordinal());
        //返回数组Season02[],含有枚举类定义的所有枚举对象
        Season02[] values = Season02.values();
        for (Season02 season: values){
            System.out.println(season);
        }
        //valueOf,将字符串转换为枚举对象,会在定义的对象中匹配已有的常量名,如果没有则报错
        Season02 spring01 = Season02.valueOf("SPRING");
        System.out.println("spring01="+spring01);
        //比较两个枚举常量的位置号,相减
        System.out.println(Season02.SPRING.compareTo(Season02.WINTER));

    }
}

Java枚举-9_第5张图片

你可能感兴趣的:(Java入门学习,java,开发语言)