好处,和传统方法比较
public class Enumeration {
public void test(){
print(Grade.A);
}
//想让下面的函数只能打印A,B,C,D
public void print(Grade g){
}
}
//方法一
/*
class Grade{
private Grade(){}
public static final Grade A = new Grade();
public static final Grade B = new Grade();
public static final Grade C = new Grade();
public static final Grade D = new Grade();
}
*/
//方法二
enum Grade{
A,B,C,D;
}
还可对枚举封装对象,改成
enum Grade{ //class A 100-90 B 89-80 C 79-70 D 69-0
A("100-90"),B("100-90"),C("100-90"),D("100-90");
private String value; //封装对应的分数
private Grade (String value){
this.value = value;
}
public String getValue(){
return this.value;
}
}
还可以改成带有抽象方法的枚举
//带抽象方法的枚举
enum Grade{ //class A 100-90 B 89-80 C 79-70 D 69-0
A("100-90"){
public String localValue(){
return "优秀";
}
}
,B("100-90"){
public String localValue(){
return "良好";
}
}
,C("100-90"){
public String localValue(){
return "一般";
}
}
,D("100-90"){
public String localValue(){
return "差";
}
};
private String value; //封装对应的分数
private Grade (String value){
this.value = value;
}
public String getValue(){
return this.value;
}
public abstract String localValue();
}