枚举和注解01:自定义类实现枚举

自定义类实现枚举

package com.enum_;

public class Enumeration01 {
    public static void main(String[] args) {
        //使用
        Season spring = new Season("春天", "温暖");
        Season winter = new Season("冬天", "寒冷");
        Season autumn = new Season("秋天", "凉爽");
        Season summer = new Season("夏天", "炎热");
        autumn.setName("~~");
        autumn.setDesc("很热");
        //因为对于季节而已,对象是固定的四个,不会有更多
        //按这个设计思路,不能体现出季节是固定的四个对象。
        //因此这样的设计不好===> 枚举类[枚:一个一个举:例举,即把具体的对象一个一个例举出来的类就称为枚举类
        Season other = new Season("~天", "~~");

    }
}
class Season{
    private String name;
    private String desc;

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }
}

因为对于季节而已,对象是固定的四个,不会有更多按这个设计思路,不能体现出季节是固定的四个对象。
因此这样的设计不好===> 枚举类[枚:一个一个举:例举,即把具体的对象一个一个例举出来的类就称为枚举类

解决方案-- n

  • enumeration – enum
  • 枚举是一组常量的几何。
  • 可以理解为:枚举属于一种特殊的类,里边只包含了一组有限的特定的对象。

枚举的两种实现方式

  • 1、自定义枚举
  • 2、使用enum关键字实现枚举

自定义实现枚举应用案例

  • 1、不需要提供setXxx方法,因为枚举对象值通常为只读
  • 2、对枚举对象/属性使用 final+ static共同修饰,实现底层优化
  • 3、枚举对象名通常使用全部大写,常量的命名规范。
  • 4、枚举对象根据需要,也可以有多个属性// EnumerationO2.java
package com.enum_;

public class Enumeration02 {
    public static void main(String[] args) {

        System.out.println(Season.AUTUMN);
        System.out.println(Season.SPRING);
        System.out.println(Season.WINTER);
        System.out.println(Season.AUTUMN);
    }
}

//演示自定义枚举实现
class Season{
    private String name;
    private String desc;
    //定义个四个对象
    public static final Season SPRING = new Season("春天", "温暖");
    public static final Season WINTER = new Season("冬天", "寒冷");
    public static final Season AUTUMN = new Season("秋天", "凉爽");
    public static final Season SUMMER = new Season("夏天", "炎热");

    //1、将构造器私有化,防止直接new出来
    //2、去掉setXxx相关的方法,防止属性被修改
    //3、在Season内部,直接创建固定的对象
    //4、优化一下,可以再加一个final 
    private Season(String name, String desc) {
        this.name = name;
        this.desc = desc;
    }

    public String getName() {
        return name;
    }



    public String getDesc() {
        return desc;
    }

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

总结

  • 1、构造器私有化
  • 2、本类内部创建一组对象
  • 3、对外暴露对象(通过为对象添加public final static修饰符)
  • 4、可以提供get方法,但是不要提供set
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值