枚举类
如何定义
方式 1 自定义
public class EnumTest {
public static void main(String[] args) {
Season spring = Season.SPRING;
System.out.println(spring);
}
}
class Season {
private final String name;
private final String detail;
private Season(String name, String detail) {
this.name = name;
this.detail = detail;
}
public final static Season SPRING = new Season("春天", "开始变暖了");
public final static Season SUMMER = new Season("夏天", "开始变热了");
public final static Season AUTUMN = new Season("秋天", "开始变凉了");
public final static Season WINTER = new Season("冬天", "开始变冷了");
public String getName() {
return name;
}
@Override
public String toString() {
return "Season{" +
"name='" + name + '\'' +
", detail='" + detail + '\'' +
'}';
}
}
方式 2 使用enum
enum Season1 {
SPRING("春天", "开始变暖了"),
SUMMER("夏天", "开始变热了"),
AUTUMN("秋天", "开始变凉了"),
WINTER("冬天", "开始变冷了");
private final String name;
private final String detail;
private Season1(String name, String detail) {
this.name = name;
this.detail = detail;
}
@Override
public String toString() {
return super.toString();
}
}
注意:
Enum类重写了toString方法,输出的是变量名。
常用方法
enum 实现接口
public class EnumTest {
public static void main(String[] args) {
Season1 winter = Season1.WINTER;
System.out.println(winter);
winter.show();
Season1 summer = Season1.valueOf("SUMMER");
summer.show();
}
}
interface Show{
void show();
}
enum Season1 implements Show{
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 name;
private final String detail;
private Season1(String name, String detail) {
this.name = name;
this.detail = detail;
}
@Override
public String toString() {
return super.toString();
}
}
Annotation 注解
自定义注解
https://www.bilibili.com/video/BV1Kb411W75N?p=507
元注解
https://www.bilibili.com/video/BV1Kb411W75N?p=508
等后面学到反射的时候再详细的看吧。