java枚舉類的定義及常用方法


java枚舉類的定義及常用方法

枚舉類是Java語言列舉類中普通基礎的一個類。定義和class類的區別是用關鍵字enum修飾。定義格式如下:

     {ClassModifierenum TypeIdentifier [ClassImplementsEnumBody

ClassModifier 默認為public,

TypeIdentifier 實際為枚舉類的類名 

 

 EnumBody 即為枚舉類的內容。

body里邊可以自定義方法。

關於文檔中的構造器定義有如下需注意的地方

1.構造器方法只能私有。如果沒有顯示聲明默認也為私有。It is a compile-time error if a constructor declaration in an enum declaration is public or protected 

2.構造器方法中不能有調用父類方法的語句。It is a compile-time error if a constructor declaration in an enum declaration contains a superclass constructor invocation statement

3.文檔中聲明的 (String name,int ordinal)的構造方法是隱式聲明 和編譯器有很大關系。

 

代碼如下:

 1 enum Color {
 2      RED, GREEN, BLACK;
 3 
 4     /**
 5      * 自有實例方法
 6      */
 7 
 8     protected void saySomething(Color col) {
 9         System.out.println("調用到我了:  " + col.toString() );
10     }
11 
12      /**
13       * 自有靜態方法
14       */
15     public  static void directCall() {
16         System.out.println("調用到靜態方法了");
17     }
18 
19 }

測試方法:

class Test {

       public static void main(String[] args) {

           System.out.println(Arrays.toString(Color.values())); //  [RED, GREEN, BLUE]

           System.out.println(Color.values()[0].getClass()); //  class com.ioc.test.enums.Color

           System.out.println(Color.valueOf("RED")); //  RED 返回枚舉值的字符串形式


           for (Color col: Color.values()) {
               System.out.println(col.ordinal()); // 返回每個枚舉值在枚舉中聲明的下標
               col.saySomething(col); // 調用枚舉類自己的實例方法
           }

          Color.directCall();


       }

輸出結果:

 valueOf(): 返回枚舉類里每個屬性的字符串值

values(): 返回枚舉類的實例。該方法由構造器提供,文檔中並未列出。

 ordinal() : 該方法由final修飾,只能由類的實例調用,返回每個枚舉值的下標


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM