一、枚舉類型作為常量
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
package myenum; /** * @author zzl * 簡單的枚舉作為常量 */ public enum Color { GREEN,RED,YELLOW; public static void main(String[] args) { for (Color c : values()) { System.out.println( "color:" +c); } } } //輸出 /** color:GREEN color:RED color:YELLOW */ |
其實在更近一步的話我們可以輸出每個枚舉實例的具體位置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
package myenum; /** * @author zzl * 簡單的枚舉作為常量 */ public enum Color { GREEN,RED,YELLOW; public static void main(String[] args) { for (Color c : values()) { System.out.println(c + " position " +c.ordinal()); } } } //輸出結果 /** GREEN position 0 RED position 1 YELLOW position 2 */ |
二、與swith結合使用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
public enum Color { GREEN,RED,YELLOW; public static void main(String[] args) { Color c = RED; switch (c) { case RED: System.out.println( "紅色" ); break ; case GREEN: System.out.println( "綠色" ); break ; case YELLOW: System.out.println( "黃色" ); break ; default : break ; } } } //輸出 /** 紅色 */ |
從上面的例子可以看出枚舉的多態性,其實可以講Color作為枚舉的超類,其中的實例在運行時表現出多態。(如上面的輸出結果為紅色,下面的例子來驗證這一特性。)
三、多態性(在Color中添加抽象方法)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
public enum Color { GREEN{ void description(){ System.out.println( "綠燈行!" ); } },RED{ void description(){ System.out.println( "紅燈停!" ); } },YELLOW{ void description(){ System.out.println( "黃燈亮了等一等!" ); } }; //如果枚舉中有方法則左后一個實例以“;”結束 abstract void description(); public static void main(String[] args) { for (Color c : values()) { c.description(); } } } <pre name= "code" class = "java" > //輸出 /** 綠燈行! 紅燈停! 黃燈亮了等一等! */ |
四、利用構造器為實例添加描述
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
public enum ColoStructure { GREEN( "綠色" ),RED( "紅色" ),YELLOW( "黃色" ); //如果枚舉中有方法則左后一個實例以“;”結束 public String description; private ColoStructure(String des){ this .description = des; } public static void main(String[] args) { for (ColoStructure c : values()) { System.out.println(c.description); } } } <pre name= "code" class = "java" ><pre name= "code" class = "java" > //輸出 /** 綠色 紅色 黃色 */ |
希望本文可以幫到有需要的朋友
原文鏈接:http://blog.csdn.net/m0_37327416/article/details/70156470