JAVA完全參考手冊(第8版) 第12章 枚舉部分

來源:互聯網
上載者:User

1、將枚舉定義為類,可以具有建構函式、方法以及執行個體變數。enum關鍵字。枚舉常量,被隱式聲明為公有靜態final成員,類型為聲明它們的類型,自類型化的。可以建立枚舉類型的變數,但不能使用new執行個體化枚舉。如,

Enum Apple { Jonathan, GoldenDel, RedDel, Winesap, Cortland }

Apple ap;  ap = Apple.RedDel;  if(ap ==
Apple.GoldenDel) ...

枚舉值也可以用於控制switch語句。枚舉常量的名稱沒有使用枚舉類型名進行限定,例如,是case RedDel,而不是case  Apple.RedDel。否則會有編譯時間錯誤。

當顯示枚舉常量時,會輸出枚舉常量的名稱。如,System.out.println(Apple.RedDel);輸出RedDel。

枚舉有兩個限制:一,不能繼承其他類;二,不能是超類,即不能擴充。

2、values()和valueOf()方法

public static enum-type [] values() 

返回一個包含枚舉常量列表的數組。可以使用for-each語句。例如for(Apple a: Apple.values()) {...}

public static enm-type valueOf(String str)

返回與傳遞到參數str的字串相對應的枚舉常量。

3、java枚舉是類類型

可以為枚舉提供建構函式、添加實力變數和方法,甚至可以實現介面。每個枚舉常量都是所屬枚舉類型的對象。

如果為枚舉類型定義了建構函式,那麼當建立每個枚舉常量時都會調用該建構函式。

枚舉繼承自Enum類,java.lang.Enum。三個常用的方法:

final int ordinal() //擷取用於指示枚舉常量在常量列表中位置的值,即原始值。

final int compareTo(enum-type e) //比較相同類型的兩個枚舉常量的原始值。返回正負數0.如ap.compareTo(ap1)。

可以使用equals()方法來比較枚舉常量和其他對象的相等性,當兩個對象都引用同一個枚舉中相同的常量時才相等。

可以使用"=="比較兩個枚舉引用。

最後例子,

enum Apple {Jonathan(10), GoldenDel(9), RedDel(12), Winesap(15), Cortland(8);private int price;Apple(int p) { price = p; }  //函數可以重載int getPrice() { return price; }}class EnumDemo {public static void main(String args[]) {Apple ap;System.out.println("Winesap costs " + Apple.Winesap.getPrice() + " cents.\n");System.out.println("All apple price:");for(Apple a: Apple.values())System.out.println(a+ " costs " + a.getPrice() + " cents.");}}

結果如下:

Winesap costs 15 cents.

All apple price:
Jonathan costs 10 cents.
GoldenDel costs 9 cents.
RedDel costs 12 cents.
Winesap costs 15 cents.
Cortland costs 8 cents.


於2013/04/10

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.