/**
*@ author StormMaybin
*@ date 2016-10-3
*/
生命不息,奋斗不止!
常量
jdk1.5之前,常量都是这么定义的
class Color
{
private String name;
private Color (String name)
{
this.name = name;
}
public static final Color GREEN = new Color("绿色");
public static final Color RED = new Color ("红色");
public static final Color BLUE = new Color ("蓝色");
}
但是jdk1.5之后,上面的代码可以简化成这样:
enum Color
{
RED("红色"), GREEN("绿色"), BLUE("蓝色");
private String name;
private Color (String name)
{
this.name = name;
}
}
向枚举中添加新方法
enum Color
{
RED("红色"), GREEN("绿色"), BLUE("蓝色");
private String name;
private Color (String name)
{
this.name = name;
}
//
public String getName ()
{
return this.name;
}
}
覆盖枚举的方法
enum Color
{
RED("红色"), GREEN("绿色"), BLUE("蓝色");
private String name;
private Color (String name)
{
this.name = name;
}
//
public String getName ()
{
return this.name;
}
@Override
public String toString()
{
return this.name;
}
}
向枚举类型中添加抽象方法
需求:定义五个枚举类型变量ABCDE,来描述分数段!并且对应的描述是A(优秀)B(良好)C(一般)D(差)E(不及格)。
enum Grade
{
A("90-100")
{
public String getLocalValue()
{
return "优秀";
}
}
, B("80-89")
{
public String getLocalValue()
{
return "良好";
}
}
, C("70-79")
{
public String getLocalValue()
{
return "一般";
}
}
, D("60-69")
{
public String getLocalValue()
{
return "差";
}
}
, E("0-59")
{
public String getLocalValue()
{
return "不及格";
}
};
private String value;
private Grade (String value)
{
this.value = value;
}
public String getValue ()
{
return this.value;
}
public abstract String getLocalValue ();
}
基本API
测试类
public class EnumTest
{
/**
* @param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub
System.out.println(Grade.A.getLocalValue());
//打印枚举类型的名字
System.out.println(Grade.A.name());
//打印枚举类型的下标
System.out.println(Grade.A.ordinal());
StringToEnum();
}
/**
* 字符串转换成类型
*/
private static void StringToEnum()
{
String str = "B";
Grade g = Grade.valueOf(Grade.class, str);
System.out.println(g);
}
}