九、枚举&注解
枚举:
自定义枚举类
//枚举类
class Season{
//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 AUTOMN = new Season("autumn","秋高气爽");
public static final Season WINTER = new Season("winter","白雪皑皑");
@Override
public String toString() {
return "Season [seasonName=" + seasonName + ", seasonDesc="
+ seasonDesc + "]";
}
public void show(){
System.out.println("这是一个季节");
}
enum关键字定义枚举类
常用的方法:value() valueOf(String name)
1.values()
Season1[] season = Season1.values();
for(int i = 0;i < season.length;i++){
System.out.println(season[i]);
}
2.valueOf(String name):要求传入的形参name是枚举类对象的名字
String str = "SPRING";
Season1 sea = Season1.valueOf(str);
让枚举类是实现接口:可以让不同的枚举类的对象调用被重写的抽象方法,执行的效果不同
enum Season extends ss{
SPRING("spring","春暖花开"){
public void show(){
System.out.println("春天");
}
},
SUMMER("summer","夏日炎炎"){
public void show(){
System.out.println("夏天");
}
},
AUTOMN("autumn","秋高气爽"){
public void show(){
System.out.println("秋天");
}
},
WINTER("winter","白雪皑皑"){
public void show(){
System.out.println("冬天");
}
};
private String seasonName;
private String seasonDesc;
private Season(String seasonName,String seasonDesc){
this.seasonName = seasonName;
this.seasonDesc = seasonDesc;
}
public String getSeasonName() {
return seasonName;
}
public String getSeasonDesc() {
return seasonDesc;
}
public String toString() {
return "Season [seasonName=" + seasonName + ", seasonDesc="
+ seasonDesc + "]";
}
注解annotation
1.JDK内置的基本注解类型(3个)
@Override:限定重写父类的方法,该注释只能用于方法
@Deprecated:用于表示某个程序元素(类,方法等)已过时
@SuppressWarnings:抑制编译器警告
2.自定义注解类型
public @interface XX{
String value() default "hellow";
}
@XX(value = "xxx")
3.对注解进行注解(4个)(原注解)
4.利用反射获取注解信息(在反射部分涉及)