Java-枚举类-引出枚举类,自定义枚举类的简单适用
引出枚举类
-
要求创建季节(Season)对像,请设计并完成
package com.tao.enum_; /** * Create By 刘鸿涛 * 2021/12/30 13:17 */ public class Enumeration01 { public static void main(String[] args) { //使用 Season spring = new Season("春天", "温暖"); Season winter = new Season("冬天", "寒冷"); Season summer = new Season("夏天", "炎热"); Season autumn = new Season("秋天", "凉爽"); autumn.setName("XXX"); 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; } }
分析问题
创建Season对象有如下特点
- 季节的值是有限的几个值(spring,summer,autumn,winter)
- 只读,不需要修改
解决方案——枚举
-
枚举对应英文(enumeration,简写 enum) 枚举是一组常量的集合 可以这样理解:枚举属于一种特殊的类,里面只包含一组有限的特定的对象
使用枚举类
package com.tao.enum_; /** * Create By 刘鸿涛 * 2021/12/30 14:49 */ public class Enumeration02 { public static void main(String[] args) { System.out.println(Season.SPRING); } } //演示定义枚举实现 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 修饰符,static为了可以直接访问 public Season(String name, String desc) { this.name = name; this.desc = desc; } public String getName() { return name; } public String getDesc() { return desc; } //重写toString() @Override public String toString() { return "Season{" + "name=" + name + + ", desc=" + desc + + }; } }
枚举类小结
- 不需要提供setXxx方法,因为枚举对象值通常为只读
- 对枚举对象/属性使用final + static 共同修饰,实现底层优化
- 枚举对象名通常使用全部大写(常量的命名规范)
- 枚举对象根据需要,也可以有多个属性
自定义类实现枚举,有如下特点
- 构造器私有化
- 本类内部创建一组对象[四个 春夏秋冬]
- 对外暴露对象(通过为对象添加public final static 修饰符)
- 可以提供get方法,但是不要提供set
上一篇:
IDEA上Java项目控制台中文乱码