枚举类型的总结
package EnumExercise; public class Student { private String name; private Grade grade; public Student(String name, Grade grade) { super(); this.name = name; this.grade = grade; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Grade getGrade() { return grade; } public void setGrade(Grade grade) { this.grade = grade; } public static void main(String[] args) { Student s=new Student("hu",Grade.A); String grade="A"; //将一个字符串转换为对应的枚举 对象 Grade g=Grade.valueOf(Grade.class, grade); System.out.println(g.toString()); //获取 枚举的类型的所有枚举 对象 Grade gs[]=Grade.values(); for(Grade tempG:gs){ System.out.println(tempG.toString()); } } } /*JDK5之后开始使用枚举类型,其实现原理与之前相同,但是实现方便*/ enum Grade{//这是简单的枚举 A,B,C,D,E//枚举对象 } enum Grade2{ A("100-90"),B("89-60"),C("59-40"),D("39-20"),E("20-0");//枚举对象 //枚举对象可以有属性 private String value; private Grade2(String value){//枚举类型的构造函数必须是私有的 this.value=value; } public String getValue() { return value; } } //为枚举类型添加方法 enum Grade3{ A("100-90"){ public String toLocalString() { // TODO Auto-generated method stub return "优"; } } ,B("89-60"){ public String toLocalString() { // TODO Auto-generated method stub return "良"; } } ,C("59-40"){ public String toLocalString() { // TODO Auto-generated method stub return "差"; } } ,D("39-20"){ public String toLocalString() { // TODO Auto-generated method stub return "很差"; } } ,E("20-0"){ public String toLocalString() { // TODO Auto-generated method stub return "极其差"; } };//枚举对象 //枚举对象可以有属性 private String value; private Grade3(String value){//枚举类型的构造函数必须是私有的 this.value=value; } public String getValue() { return value; } //定义一个抽象方法,然后在各自的实例对象中实现各自需要的方法 public abstract String toLocalString(); } /*JDK5以前实现控制字段只能在固定范围之间取值的方法 class Grade { private Grade(){ } Grade A=new Grade(); Grade B=new Grade(); Grade C=new Grade(); Grade D=new Grade(); } */