首页 > 代码库 > 枚举类的介绍
枚举类的介绍
- 枚举类,即对象为可穷举的类
- JDK 1.5 新增的 enum 关键字用于定义枚举类,在这之前,需要自定义枚举类
- 若枚举只有一个成员(对象),则可以作为一种单例模式的实现方式——单例(单子)设计模式(Singleton)
自定义枚举类:
public class TestSeason {
public static void main(String[] args) {
Season spring = Season.SPRING;
Season summer = Season.SUMMER;
Season autumn = Season.AUTUMN;
Season winter = Season.WINTER;
System.out.println(spring);// Season [seasonName=春天]
System.out.println(summer);// Season [seasonName=夏天]
System.out.println(autumn);// Season [seasonName=秋天]
System.out.println(winter);// Season [seasonName=冬天]
}
}
class Season {
// 1.提供以 private final 修饰的类属性
private final String seasonName;
// 2.在以 private 修饰的构造器中初始化类属性
private Season(String seasonName) {
this.seasonName = seasonName;
}
// 3.提供公共的方法来调用属性
public String getSeasonName() {
return this.seasonName;
}
// 4.创建以 public static final 修饰的该枚举类的对象
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 [seasonName=" + seasonName + "]";
}
}
使用 enum 关键字定义枚举类及其特性:
public class TestSeason {
public static void main(String[] args) {
Season spring = Season.SPRING;
Season summer = Season.SUMMER;
Season autumn = Season.AUTUMN;
Season winter = Season.WINTER;
System.out.println(spring);// Season [seasonName=春天]
System.out.println(summer);// Season [seasonName=夏天]
System.out.println(autumn);// Season [seasonName=秋天]
System.out.println(winter);// Season [seasonName=冬天]
// 枚举类常用的方法
// 1.以数组的形式返回所有枚举类的对象:values();
Season[] seasons = Season.values();
for (Season s : seasons) {
System.out.println(s);
} // Season [seasonName=春天]
// Season [seasonName=夏天]
// Season [seasonName=秋天]
// Season [seasonName=冬天]
// 2.返回以指定字符串为对象名的对象(要求形参 str 是枚举对象的名字,
// 否则报IllegalArgumentException):valueOf(String str);
String str = "SPRING";
System.out.println(Season.valueOf(str).getSeasonName());// 春天
// 接口的特殊实现
Season.valueOf(str).show();// 春暖花开
}
}
interface Info {
void show();
}
enum Season implements Info {
// 与自定义枚举类对比:对象声明要放最前面,重复的部分删除,对象之间以逗号分隔
// 枚举类实现接口,可以让不同对象以不同的方式实现接口中的抽象方法(也可以让类
// 实现,各对象共享)
SPRING("春天") {
public void show() {
System.out.println("春暖花开");
}
},
SUMMER("夏天") {
public void show() {
System.out.println("夏日炎炎");
}
},
AUTUMN("秋天") {
public void show() {
System.out.println("秋高气爽");
}
},
WINTER("冬天") {
public void show() {
System.out.println("白雪皑皑");
}
};
private final String seasonName;
private Season(String seasonName) {
this.seasonName = seasonName;
}
public String getSeasonName() {
return this.seasonName;
}
@Override
public String toString() {
return "Season [seasonName=" + seasonName + "]";
}
}
枚举类的介绍
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。