根据尚硅谷的视频做的JUC学习笔记
目录
一、枚举类的创建
1. 自定义枚举类
步骤:(1)声明Season对象的属性:private final修饰(2)2.私有化类的构造器,并给对象属性赋值(3)提供当前枚举类的多个对象:public static final的(4)其他诉求
public class SeasonTest {
public static void main(String[] args) {
Season spring = Season.SPRING;
System.out.println(spring);
}
}
//自定义枚举类
class Season{
//1.声明Season对象的属性:private final修饰
private final String seasonName;//季节名称
private final String seasonDesc;//季节描述
//2.私有化类的构造器,并给对象属性赋值
public Season(String seasonName, String seasonDesc) {
this.seasonName = seasonName;
this.seasonDesc = seasonDesc;
}
//3.提供当前枚举类的多个对象: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("冬天","冰天雪地");
//4.其他诉求1:获取枚举类对象的属性
public String getSeasonName() {
return seasonName;
}
public String getSeasonDesc() {
return seasonDesc;
}
//4.其他诉求2:提供toString()方法
@Override
public String toString() {
return "Season{" +
"seasonName='" + seasonName + '\'' +
", seasonDesc='" + seasonDesc + '\'' +
'}';
}
}
2. 使用 enum 关键字定义枚举类
步骤:(1)提供当前枚举类的多个对象,多个对象之间用逗号隔开,末尾使用分号结束(2)声明Season对象的属性:private final修饰(3)私有化类的构造器,并给对象属性赋值(4)其他诉求
public class SeasonTest1 {
public static void main(String[] args) {
Season1 summer = Season1.SUMMER;
System.out.println(summer);//SUMMER
System.out.println(summer.getSeasonName());//夏天
System.out.println(Season1.class.getSuperclass());//class java.lang.Enum
}
}
//使用enum关键字定义枚举类
enum Season1 {
//1.提供当前枚举类的多个对象,多个对象之间用逗号隔开,末尾使用分号结束
SPRING("春天", "春暖花开"),
SUMMER("夏天", "夏日炎炎,有你超甜"),
AUTUMN("秋天", "秋高气爽"),
WINTER("冬天", "冰天雪地");
//2.声明Season对象的属性:private final修饰
private final String seasonName;//季节名称
private final String seasonDesc;//季节描述
//3.私有化类的构造器,并给对象属性赋值
private Season1(String seasonName, String seasonDesc) {
this.seasonName = seasonName;
this.seasonDesc = seasonDesc;
}
//4.其他诉求:获取枚举类对象的属性
public String getSeasonName() {
return seasonName;
}
public String getSeasonDesc() {
return seasonDesc;
}
}
说明:定义的枚举类默认继承于
java.lang.Enum
类
二、Enum 类中的常用方法
三、使用 enum 关键字定义的枚举类实现接口
1. 实现接口,在enum类中实现抽象方法
public class Test1 {
public static void main(String[] args) {
STATUS busy = STATUS.BUSY;
busy.show();//一种状态
}
}
interface Info {
void show();
}
enum STATUS implements Info {
FREE("自由人"),
BUSY("忙碌中");
private final String status;
STATUS(String status) {
this.status = status;
}
@Override
public void show() {
System.out.println("一种状态");
}
}
2. 让枚举类的对象分别实现接口中的抽象方法
public class Test2 {
public static void main(String[] args) {
STATUS1[] values = STATUS1.values();
for (int i = 0; i < values.length; i++) {
values[i].show();//自由的飞翔 匆匆忙忙,慌慌张张
}
}
}
interface Info2 {
void show();
}
enum STATUS1 implements Info2 {
FREE("自由人") {
@Override
public void show() {
System.out.println("自由的飞翔");
}
},
BUSY("忙碌中") {
@Override
public void show() {
System.out.println("匆匆忙忙,慌慌张张");
}
};
private final String status;
STATUS1(String status) {
this.status = status;
}
}