一.枚举介绍
1.枚举是一组常量的集合 2.理解:美剧属于一种特殊的类,里面只包含一组有限的特定的对象
1.自定义枚举实现
1.不需要提供Set方法,枚举对象值通常为只读。 2.对枚举对象/属性使用final和static关键字修饰,实现底层优化 3.枚举对象名通常使用全部大写,常量的命名规范 4.枚举·对象根据需要,可以有一到多个属性
(1)示例
package com.demo;
import javax.sound.midi.Soundbank;
public class Enum01 {
public static void main(String[] args) {
System.out.println(Season.SPRING);
System.out.println(Season.SUMMER);
System.out.println(Season.AUTUMN);
System.out.println(Season.WINTER);
}
}
class Season{
private String name;
private String desc;
private Season(String name, String desc) {
this.name = name;
this.desc = desc;
}
public String getName() {
return name;
}
public String getDesc() {
return desc;
}
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("冬天","寒冷");
@Override
public String toString() {
return "Season{" +
"name='" + name + '\'' +
", desc='" + desc + '\'' +
'}';
}
}
(2)测试结果
2.enum关键字实现枚举
如果使用enum关键字来实现枚举类 1.使用关键字enum替换class 2.public static final Season02 SPRING=new Season02(“春天”,“温暖”);可替换为 SPRING(“春天”,“温暖”),//解读:常量名(实参列表) 3.如果有多个常量使用逗号间隔即可 4.如果使用enum关键字实现枚举,要求将定义的常量对象写下前面
(1)示例
package com.demo;
public class Enum02 {
public static void main(String[] args) {
System.out.println(Season.SPRING);
System.out.println(Season.SUMMER);
System.out.println(Season.AUTUMN);
System.out.println(Season.WINTER);
}
}
enum Season02{
SPRING("春天","温暖"),
SUMMER("夏天","炎热"),
AUTUMN("秋天","凉爽"), 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;
}
@Override
public String toString() {
return "Season{" +
"name='" + name + '\'' +
", desc='" + desc + '\'' +
'}';
}
}
(2)测试结果
3.enum关键字注意事项
1.当我i们使用enum关键字开发一个枚举类时,默认会继承Enum类 2.传统的public static final Season02 SPRING=new Season02("春天","温暖"); ,这里要知道他调用的是哪个构造器 3.如果使用无参构造器创建枚举对象,则实参列表和小括号都可以省略. 4.当有多个枚举对象时,使用逗号间隔,最后有一个分号结尾 5.枚举对象必须放在枚举类的行首
(1)示例
package com.demo;
public class Enum02 {
public static void main(String[] args) {
System.out.println(Season.SPRING);
System.out.println(Season.SUMMER);
System.out.println(Season.AUTUMN);
System.out.println(Season.WINTER);
}
}
enum Season02{
SPRING("春天","温暖"),
SUMMER("夏天","炎热"),
AUTUMN("秋天","凉爽"), WINTER("冬天","寒冷"),
HAHA,
HAHAHA();
private String name;
private String desc;
private Season02(String name, String desc) {
this.name = name;
this.desc = desc;
}
private Season02() {
}
public String getName() {
return name;
}
public String getDesc() {
return desc;
}
@Override
public String toString() {
return "Season{" +
"name='" + name + '\'' +
", desc='" + desc + '\'' +
'}';
}
}
|