Java枚舉小結
-
如何定義一個枚舉類?
1 //定義了4個等級 2 enum Level{ 3 A,B,C,D 4 } -
枚舉類的實質:
class Level{ public static final Level A = new Level(); public static final Level B = new Level(); public static final Level C = new Level(); public static final Level D = new Level(); }
-
枚舉類可以定義構造方法,屬性,方法
enum Level{ A("85~100","優"), B("75~84","良"), C("60~74","中"), D("60以下","差"); private String score; private String ctype; private Level(String score,String ctype){ //構造方法必須是私有的 this.score = score ; this.ctype = ctype; } public String getscore(){ return this.score; } public String getctpye(){ return this.ctype; } } public class Enumation { public static void main(String[] args) { System.out.println(Level.A.getscore()); System.out.println(Level.A.getctpye()); Level[] ls = Level.values(); } } //輸出結果 //85~100 //優
- 帶抽象方法的枚舉類
enum Level{ A("85~100"){ @Override public String getctpye() { return "優"; } }, B("75~84") { @Override public String getctpye() { return "良"; } }, C("60~74") { @Override public String getctpye() { return "中"; } }, D("60以下") { @Override public String getctpye() { return "差"; } }; private String score; private Level(String score){ this.score = score ; } public String getscore(){ return this.score; } public abstract String getctpye(); //每個對象都要重寫抽象方法 }
-
常用方法
public class Enumation { public static void main(String[] args) { System.out.println(Level.C.name()); //返回枚舉常量的名稱 System.out.println(Level.C.ordinal()); //返回枚舉常量的序號(下標從0開始) Level[] ls = Level.values(); //遍歷枚舉類型 for(Level l :ls){ System.out.println(l); } String letter = "B" ; //返回帶指定名稱的指定枚舉類型的枚舉常量,若letter為非枚舉類型會拋異常java.lang.IllegalArgumentException: No enum constant Level b = Level.valueOf(letter); System.out.println(b.B); } }
輸出:
C
2
A
B
C
D
B
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!