枚举类:为什么要又枚举类?有一些类中的对象是有限个的,可以枚举出来
1.如何自定义枚举类
//1.提供类的属性,声明为private final,
private final String seasonName;
private final String seasonDesc;
//2.私有化构造器,声明为final的属性在构造器中初始化
private Season(String seasonName,String seasonDesc){
this.seasonName = seasonName;
this.seasonDesc = seasonDesc;
}
//3.通过公共的方法来调用属性
public String getSeasonName() {
return seasonName;
}
public String getSeasonDesc() {
return seasonDesc;
}
//4.创建枚举类的对象,将类的对象声明为public static final
public static final Season SPRING = new Season("spring", "春暖花开");
public static final Season SUMMER = new Season("summer", "夏日炎炎");
public static final Season AUTUMN = new Season("autumn", "秋高气爽");
public static final Season WINTER = new Season("winter", "白雪皑皑")
2.如何使用enum关键字定义枚举类
enum Season{
SPRING("spring", "春暖花开"),
SUMMER("summer", "夏日炎炎"),
AUTUMN("autumn", "秋高气爽"),
WINTER("winter", "白雪皑皑");
常用的方法
//1.values():以数组的方式返回枚举类的所有对象
Season1[] seasons = Season1.values();
for(int i = 0 ; i < seasons.length ;i++){
System.out.println(seasons[i]);
}
//2.valueOf(String name):要求传入的形参name是枚举类对象的名
//否则报java.lang.IllegalArgumentException的异常
String str = "SUMMER1";
Season1 sea = Season1.valueOf(str);
System.out.println(sea);
如何让枚举类实现接口:可以让不同的枚举类的对象调用的抽象方法不一样
让每个对象重写抽象方法
SPRING("spring", "春暖花开"){
public void show(){
System.out.println("春天来临了");
}
}
注解
常用的注解
注解主要关注两个关键字:
Target ,指明注解可以使用的范围
Retention ,指明注解的声明周期
(SOURCE,编译时抛弃)
(CLASS,编译时保留,运行时抛弃)
(RUMTIME,运行时保留,可用反射获取)
元注解:修饰“注解”的注解