举个例子,比如:如果是CAT,需要鱼,MONKEY需要香蕉,PANDA 吃竹子...
那么我们需要这样写if-else
public static void main(String[] args) {
String animal = "PANDA";
String food = animalEatByType(animal);
System.out.println(food);
}
private static String animalEatByType(String type) {
if ("PANDA".equals(type)) {
return "吃竹子";
} else if("CAT".equals(type)) {
return "吃鱼";
} else if("MONKEY".equals(type)) {
return "吃香蕉";
}
return null;
}
使用枚举后,我们只需要向枚举类中添加类型即可:
public enum AnimalEnum {
CAT {
@Override
public String toDo() {
//....复杂操作
return "吃鱼";
}
},
PANDA {
@Override
public String toDo() {
return "吃竹子";
}
},
MONKEY {
@Override
public String toDo() {
return "吃香蕉";
}
};
//定义要做的抽象方法,由每个枚举实现
public abstract String toDo();
}
调用:
AnimalEnum animalEnum = AnimalEnum.valueOf(animal);
String aDo = animalEnum.toDo();
System.out.println(aDo);
但是可能出现 CAT,MONKEY都吃香蕉的情况,我们可以在枚举类中再定义一个内部枚举来进行扩充
public enum AnimalExtEnum {
CAT("CAT", AnimalExtEnum.Type.FASH),
PANDA("PANDA", AnimalExtEnum.Type.ZHUZI),
MONKEY("MONKEY", AnimalExtEnum.Type.FASH);
private final String animal;
private final Type type;
public String toDo(){
return type.toDo();
}
AnimalExtEnum(String animal,Type type) {
this.type = type;
this.animal = animal;
}
private enum Type {
FASH{
@Override
public String toDo() {
return "吃鱼";
}
},
ZHUZI{
@Override
public String toDo() {
return "吃竹子";
}
};
public abstract String toDo();
}
}
调用:
String animal = "MONKEY";
AnimalExtEnum animalExtEnum = AnimalExtEnum.valueOf(animal);
String aDo = animalExtEnum.toDo();
System.out.println(aDo);
标签:return,String,type,else,枚举,animal,toDo,public,消除
From: https://blog.csdn.net/m0_73363097/article/details/141503071