枚举定义
public enum Week {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY;
//无参构造器,默认private
Week(){
System.out.println("hello");
}
}
public class Test {
public static void main(String[] args) {
Week w = Week.FRIDAY;
}
}
有参构造和枚举类成员
public enum Week {
SUNDAY(7), MONDAY(1), TUESDAY(2), WEDNESDAY(3), THURSDAY(4), FRIDAY(5), SATURDAY(6);
private int weekNum;
Week(int weekNum){
this.weekNum = weekNum;
}
public int getWeekNum() {
return weekNum;
}
}
public class Test {
public static void main(String[] args) {
Week w = Week.FRIDAY;
System.out.println(w.getWeekNum()); //5
}
}
枚举中的抽象方法
public enum Week {
SUNDAY(){
@Override
public void getWeekNum() {
System.out.println(7);
}
},
MONDAY() {
@Override
public void getWeekNum() {
System.out.println("星期一");
}
},
TUESDAY(){
@Override
public void getWeekNum() {
System.out.println("礼拜二");
}
},
WEDNESDAY(){
@Override
public void getWeekNum() {
System.out.println("周三");
}
};
public abstract void getWeekNum();
}
public class Test {
public static void main(String[] args) {
Week w = Week.TUESDAY;
w.getWeekNum(); //礼拜二
}
}
每个枚举类都有两个 static 方法:
- static Direction[] values():返回本类所有枚举常量;
- static Direction valueOf(String name):通过枚举常量的名字返回Direction常量,注意,这个方法与Enum类中的valueOf()方法的参数个数不同。
public class Test {
public static void main(String[] args) {
for (Week w : Week.values()) {
System.out.println(w);
}
System.out.println("星期天:" + Week.valueOf("SUNDAY"));
}
}
=====================================================================
枚举应用
一、传入商品折扣计算价格
public enum Discount {
EIGHT_DISCOUNT(0.8), SIX_DISCOUNT(0.6), FIVE_DISCOUNT(0.5);
private double discountNum;
Discount(double discountNum) {
this.discountNum = discountNum;
}
double getDiscountNum(){
return discountNum;
}
}
public class Test {
public static void main(String[] args) {
calculatePrice(Discount.EIGHT_DISCOUNT);//0.8
}
static BigDecimal calculatePrice(Discount discount){
System.out.println(discount.getDiscountNum());
//...
return null;
}
}
二、switch使用
public class Test {
public static void main(String[] args) {
Week w = Week.MONDAY; //周一
switch (w) {
case MONDAY:
System.out.println("周一"); break;
case TUESDAY:
System.out.println("周二"); break;
}
}
}
三、实现接口,消除if/else
原案例:
if ("dog".equals(animalType)){
System.out.println("吃骨头");
} else if ("cat".equals(animalType)) {
System.out.println("吃鱼干");
} else if ("sheep") {
System.out.println("吃草");
}
①、先定义一个接口
public interface Eat {
//吃
String eat();
}
②、创建枚举类实现这个接口
public enum AnimalEnum implements Eat {
Dog(){
@Override
public void eat() {
System.out.println("吃骨头");
}
},
Cat() {
@Override
public void eat() {
System.out.println("吃鱼干");
}
},
Sheep() {
@Override
public void eat() {
System.out.println("吃草");
}
}
}
public class Test {
public static void main(String[] args) {
AnimalEnum.valueOf("Cat").eat();
}
}
Java 中其实还有专门用于枚举的集合类,EnumSet 和 EnumMap