結合Android例子理解Java enum

能夠把 enum 當作是一個普通的 class,它們均可以定義一些屬性和方法,不一樣之處是:enum 不能使用 extends 關鍵字繼承其餘類,由於 enum 已經繼承了 java.lang.Enum(java是單一繼承)。
參考自: http://www.cnblogs.com/hemingwang0902/archive/2011/12/29/2306263.html html

Android framework 中的例子以下: java

From  DataConnection.java   
public enum FailCause {
        NONE(0),       
        // This series of errors as specified by the standards
        // specified in ril.h
        OPERATOR_BARRED(0x08),
        INSUFFICIENT_RESOURCES(0x1A),
        MISSING_UNKNOWN_APN(0x1B),
        UNKNOWN_PDP_ADDRESS_TYPE(0x1C),
        USER_AUTHENTICATION(0x1D), htm

       ...
        private final int mErrorCode;
        private static final HashMap<Integer, FailCause> sErrorCodeToFailCauseMap;
        static {
            sErrorCodeToFailCauseMap = new HashMap<Integer, FailCause>();
            for (FailCause fc : values()) {
                sErrorCodeToFailCauseMap.put(fc.getErrorCode(), fc);
            }
        } blog

        FailCause(int errorCode) {
            mErrorCode = errorCode;
        } 繼承

        int getErrorCode() {
            return mErrorCode;
        }

        public static FailCause fromInt(int errorCode) {
            FailCause fc = sErrorCodeToFailCauseMap.get(errorCode);
            if (fc == null) {
                fc = UNKNOWN;
            }
            return fc;
        }

        ...
} ci

如何來使用呢?
FailCause mFailCause = FailCause.NONE;
或FailCause mFailCause = FailCause.fromInt(0x08); get

相關文章
相關標籤/搜索