JT's Blog

Do the right things and do the things right.

Java Enum

| Comments

在J2SE 5.0 之前,沒有Enum

使用staticfinal兩個修飾詞建立常數變數

  • static:class variable, class 未被instance 就被宣告完成且可以使用、所有class 是參考同一個變數
  • final:使用之後此變數即是常數,無法被繼承也無法被修改
1
2
3
4
5
6
7
8
public Class StateMachines {
    public static final String ORDER_PLACED = "1";
    public static final String PAID = "2";
    public static final String SHIPPING = "3";
    public static final String SHIPPED = "4";
    public static final String ORDER_CANCELLED = "5";
    public static final String GOOD_RETURNED = "6";
}

Enum 使用方法

  1. 定義常數,例如要定義購買流程狀態,就定出已下訂、已付款…等代碼
1
2
3
public enum StateMachines {
    ORDER_PLACED,PAID,SHIPPING,SHIPPED,ORDER_CANCELLED,GOOD_RETURNED;
}
  1. 定義常數內容、overriding、switch case
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public enum StateMachines {
      ORDER_PLACED(1),PAID(2),SHIPPING(3),SHIPPED(4),ORDER_CANCELLED(5),GOOD_RETURNED(6);

        private int step;

        private Direction(int step) {
          this.step = step;
        }

        @Override
        public String toString() {
          return String.valueOf(this.step);
        }

        public String getChName() {
          switch(this) {
          case ORDER_PLACED:
            return "已下訂";
          case PAID:
            return "已付款";
            // 略
          }
      }
}

結論

  1. enum 不可繼承其他類別
  2. 可新增method 在enum 內
  3. 可overriding 原enum 的method
  4. switch 可使用enum 作為判斷
  5. 歸納同性質的常數,並可以衍生共用method
  6. 常數的泛型化應用

Reference

Comments