JAVA枚舉類型的使用舉例,下面的代碼經本人測試,望對Java枚舉類型不解的人有所幫助。
- /**
- * This class presents a application of the enum(枚舉) class.
- * @author HAN
- *
- */
- public class EnumApps {
- public enum Constants{ //枚舉類型
- Constants_A("HAN"),
- Constants_B("Gaowen"),
- Constants_C(23);
- private String s;
- private Constants(String s){ //多態
- this.s=s;
- }
- private int i;
- private Constants(int i){
- this.i=i;
- }
- private String getString(){
- return s;
- }
- private int getInt(){
- return i;
- }
- }
-
- private Object value(Constants c){
- Object o;
- switch(c){
- case Constants_A:
- o=Constants.Constants_A.getString();
- break;
- case Constants_B:
- o= Constants.Constants_B.getString();
- break;
- case Constants_C:
- o= Constants.Constants_C.getInt();
- break;
- default:
- o= null;
- }
- return o;
- }
- public static void main(String[] args){
- EnumApps instance1=new EnumApps();
- System.out.println(instance1.value(Constants.Constants_A));
- System.out.println(instance1.value(Constants.Constants_B));
- System.out.println(instance1.value(Constants.Constants_C));
- System.out.printf("\n");
- for(int i=0;i<Constants.values().length;i++){
- System.out.println(instance1.value(Constants.values()[i]));
- }
- }
- }