Skip to content

Commit feabae9

Browse files
committed
Update CH11.md
1 parent cf5c2e7 commit feabae9

File tree

1 file changed

+8
-0
lines changed

1 file changed

+8
-0
lines changed

docs/CH11.md

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ public interface ActionConstants {
2525

2626
共用的常數通常是可以直接取用並且不可被修改的,所以您在宣告時加上 "static" 與 "final",如此您可以在程式中直接使用像是 ActionConstants.TURN_LEFT 的名稱來取用常數值,例如:
2727

28+
```java
2829
public void someMethod() {
2930
....
3031
doAction(ActionConstants.TURN_RIGHT);
@@ -43,6 +44,7 @@ public interface ActionConstants {
4344
break;
4445
}
4546
}
47+
```
4648

4749
如果使用類別來宣告的話,方法也是類似,例如:
4850

@@ -68,6 +70,7 @@ public class CommandTool {
6870

6971
您已經知道可以在類別或介面中宣告常數來統一管理常數,這只是讓您存取與管理常數方便而已,來看看這個例子:
7072

73+
```java
7174
public void someMethod() {
7275
....
7376
doAction(ActionConstants.TURN_RIGHT);
@@ -81,18 +84,21 @@ public class CommandTool {
8184
..
8285
}
8386
}
87+
```
8488

8589
這種作法本身沒錯,只不過 doAction() 方法接受的是int型態的常數,您沒有能力阻止程式設計人員對它輸入 ActionConstants 規定外的其它常數,也沒有檢查 "switch" 中列舉的值是不是正確的值,因為參數 action 就只是 int 型態而已,當然您可以自行設計一些檢查動作,這需要一些額外的工作,如果您使用 J2SE 5.0 中新增的「列舉型態」(Enumerated Types),就可以無需花額外的功夫就輕易的解決這些問題。
8690

8791
在 J2SE 5.0 中要定義列舉型態是使用 "enum" 關鍵字,以下先來看看列舉型態的應用,舉個實際的例子,範例 11.3 是定義了 Action 列舉型態。
8892

8993
#### **範例 11.3 Action.java**
9094

95+
```java
9196
public enum Action {
9297
TURN_LEFT,
9398
TURN_RIGHT,
9499
SHOOT
95100
}
101+
```
96102

97103
不用懷疑,在 Action.java 中撰寫範例 11.3 的內容然後編譯它,雖然語法上不像是在定義類別,但列舉型態骨子裏就是一個類別,所以您編譯完成後,會產生一個 Action.class 檔案。
98104

@@ -128,6 +134,7 @@ public class EnumDemo {
128134
除了讓您少打一些字之外,這個範例好像沒有什麼特別的,但注意到 doAction() 參數列的型態是 Action,如果您對 doAction() 方法輸入其它型態的引數,編譯器會回報錯誤,因為 doAction() 所接受的引數必須是 Action 列舉型態。
129135
使用列舉型態還可以作到更進一步的檢驗,如果您在 "switch" 中加入了不屬於 Action 中列舉的值,編譯器也會回報錯誤,例如:
130136

137+
```java
131138
...
132139
public static void doAction(Action action) {
133140
switch(action) {
@@ -145,6 +152,7 @@ public class EnumDemo {
145152
break;
146153
}
147154
} ...
155+
```
148156

149157
在編譯時編譯器會替您作檢查,若檢查出不屬於 Action 中的列舉值,會顯示以下的錯誤:
150158

0 commit comments

Comments
 (0)