JAVA学习之枚举

时间:2022-12-26 00:18:00

1、新建一个枚举类

public enum Apple{
FUJI,
PIPPIN,
GRANNY_SMITH
}

通过查看字节码,可以看到,枚举类的实现方式:

1)继承自java.lang.Enum类。

2)构造类为private

3)枚举内的元素通过static域来引用

2、在枚举类中添加任意的方法和域。

public enum Apple {
FUJI("red"),
PIPPIN("green"),
GRANNY_SMITH("orange"); private String color; Apple(String color) {
this.color = color;
}
  public String getColor() {
  return color;
  }
}

在上面的类中:

1)添加了域color

2)创建了新的构造函数。

3)增加了新的方法。

3、在枚举中声明抽象方法,特定于常量的方法实现。

public enum Operation {

    PLUS {
@Override
double apply(double x, double y) {
return x+y;
}
},
MINUS {
@Override
double apply(double x, double y) {
return x-y;
}
},
TIMES {
@Override
double apply(double x, double y) {
return x*y;
}
},
DIVIDE {
@Override
double apply(double x, double y) {
return x/y;
}
}; abstract double apply(double x,double y);
}

针对每个枚举值,分别定义不同的方法实现。

4、策略枚举

public enum PayrollDay {
MONDAY(PayType.WEEDAY),
TUESDAY(PayType.WEEDAY),
WEDNESDAY(PayType.WEEDAY),
THURSDAY(PayType.WEEDAY),
FRIDAY(PayType.WEEDAY),
SATURDAY(PayType.WEEKEND),
SUNDAY(PayType.WEEKEND); private final PayType payType; PayrollDay(PayType payType) {
this.payType = payType;
} double pay(double houresWorked, double payRate){
return payType.pay(houresWorked, payRate);
} private enum PayType{
WEEDAY {
@Override
double overtimePay(double hrs, double payRate) {
return hrs<=HOURS_PER_SHIFT ? 0 :
(hrs - HOURS_PER_SHIFT) * payRate / 2;
}
},
WEEKEND {
@Override
double overtimePay(double hrs, double payRate) {
return hrs * payRate / 2;
}
}; private static final int HOURS_PER_SHIFT=8; abstract double overtimePay(double hrs, double payRate); double pay(double hoursWorked, double payRate){
double basePay = hoursWorked * payRate;
return basePay + overtimePay(hoursWorked,payRate);
}
} }

针对常量如果可以进行分类,则可以定义一个策略枚举,来减少样板代码