JDK5.0新特性-枚举

 

//静态导入:导入这个类里面的静态方法 import static java.lang.System.out; /** * 枚举类的一些简单例子.
* @author 贺少辉.
* create 2010-07-19. */ public class TestEnum{ public static void main(String[] args) { //获取所有枚举对象 Season2[] ss = Season2.values(); for(Season2 s : ss){ out.println(s.ordinal() + "--->" + s.name()); } //获取单个枚举对象. Season1 s = Enum.valueOf(Season1.class , "SPRING"); Season2 s2 = Season2.SPRING; //应用实例 //1:加、减、乘、除 Operator[] op = Operator.values(); for(Operator o: op){ out.println(o.getName() + "("+o.name()+") : " + o.calculate(4,2)); } //2:switch case String action=""; switch(Season1.valueOf(action)){ case AUTUMN: break; } } } //最简单的枚举定义. enum Season1{ SPRING, SUMMER, AUTUMN, WINTER; } enum Season2 { SPRING("春天"), SUMMER("夏天"), AUTUMN("秋天"), WINTER("冬天"); //属性可以通过构造方法和set方法设置. private String name; private String age; private Season2(String name){ this.name = name; } public String getName(){ return this.name; } public void setAge(String age){ this.age = age; } public String getAge(){ return this.age; } } class A{} //enum Season3 extends A{} //Error 枚举不能继承一个类 //class B extends Season2{} //Error 类不能继承一个枚举 interface IA{ public void print(); } //枚举实现接口:1:接口的方法由枚举对象实现. 2:枚举对象可以不实现接口的方法. 3:外部调用时当没有实现也不会报错. enum Season3 implements IA{ SPRING{ public void print(){ } }, SUMMER, AUTUMN, WINTER; public void print(){} } enum Operator{ ADD("加"){ public int calculate(int i, int j){ return i+j; } }, MINUS("减"){ public int calculate(int i, int j){ return i-j; } }, MULTIPLY("乘"){ public int calculate(int i, int j){ return i*j; } }, DIVIDE("除"){ public int calculate(int i, int j){ return i/j; } }; private String name; private Operator(String name){ this.name = name; } public String getName(){ return this.name; } public abstract int calculate(int i, int j); }

 

你可能感兴趣的:(java基础)