大家好呀!我是小笙!我学习了韩顺平老师的类和对象的知识,收获颇丰!现在来和大家分享笔记!
枚举和注解
概念:枚举是一种特殊的类,里面只包含一组有限的特定的对象
自定义枚举
public class EnumClass01 {
public static void main(String[] args) {
System.out.println(EnumDemo.WINTER);
System.out.println(EnumDemo.SUMMER);
System.out.println(EnumDemo.AUTUMN);
System.out.println(EnumDemo.SPRING.toString());
}
}
class EnumDemo{
private String seasonName;
private String seasonFeature;
public String getSeasonFeature() {
return seasonFeature;
}
public String getSeasonName() {
return seasonName;
}
private EnumDemo(String seasonName,String seasonFeature){
this.seasonName = seasonName;
this.seasonFeature = seasonFeature;
}
final static EnumDemo SPRING = new EnumDemo("春天","温暖");
final static EnumDemo SUMMER = new EnumDemo("夏天","炎热");
final static EnumDemo AUTUMN = new EnumDemo("秋天","凉爽");
final static EnumDemo WINTER = new EnumDemo("冬天","寒冷");
@Override
public String toString() {
return "["+getSeasonName()+"--->"+getSeasonFeature()+"]";
}
}
enum关键字实现枚举
public class EnumClass02 {
public static void main(String[] args) {
System.out.println(Session.AUTUMN);
}
}
enum Session{
SPRING("春天","温暖"),
SUMMER("夏天","炎热"),
AUTUMN("秋天","凉爽"),
WINTER("冬天","寒冷");
private String seasonName;
private String seasonFeature;
public String getSeasonFeature() {
return seasonFeature;
}
public String getSeasonName() {
return seasonName;
}
private Session(String seasonName,String seasonFeature){
this.seasonName = seasonName;
this.seasonFeature = seasonFeature;
}
@Override
public String toString() {
return "["+getSeasonName()+"--->"+getSeasonFeature()+"]";
}
}
枚举常用方法
enum Week{
MONDAY("星期一"),TUESDAY("星期二"),WEDNESDAY("星期三"),THURSDAY("星期四"),FRIDAY("星期五"),SATURDAY("星期六"),SUNDAY("星期日");
private String WeekName;
private Week(String WeekName) {
this.WeekName = WeekName;
}
}
class testMethod{
public static void main(String[] args) {
Week f = Week.FRIDAY;
System.out.println(f.toString());
System.out.println(f.toString() == f.name());
System.out.println(f.ordinal());
for (int i = 0; i < Week.values().length; i++) {
System.out.print(Week.values()[i]+" ");
}
System.out.println();
Week m = Week.valueOf("MONDAY");
System.out.println(m.toString());
System.out.println(m.compareTo(f));
}
}
注解与元注解
注解
概念:注解是绑定到程序源代码元素的元数据,对运行代码的操作没有影响。
三个基本注解: @Deprecated @Override @SuppressWarnings
public class Deprecated_ {
public static void main(String[]args){
A a = new A();
}
}
@Deprecated
class A{
public void fly(){}
}
class B extends A{
@Override
public void fly(){}
}
元注解(了解)
概念: 用来修饰注解(如@Override)
Retention 指定注解的作用范围,三种SOURCE,CLASS,RUNTIME
- RetentionPolicy.SOURCE 该注解经过编译后被丢弃
- RetentionPolicy.CLASS 该注解在解释之后被丢弃
- RetentionPolicy.RUNTIME 该注解会被保存到JVM虚拟机中
Target 指定注解可以在哪些地方使用
Documented 指定该注解是否会在javadoc体现
Inherited 子类会继承父类的注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Override {
}
|