2011-12-13 73 views
3

是否可以像這樣在Android中使用Enum?Java枚舉可以添加一個返回方法嗎?

public enum EventAction 
{ 
    SDCARD_MOUNTED 
    { 
    public String toString() { 
     return "External SDCard was mounted"; 
    } 

    public int getCode() { 
     return 25; 
    } 
    } 
} 

從外部的代碼我只有EventAction.SDCARD_MOUNTED.toString(),但.getCode()的訪問是不可見的。我看到的例子展示瞭如何從代碼中使用getCode()。

回答

8

申報getCode()作爲abstract方法:

public enum EventAction 
{ 
    SDCARD_MOUNTED 
    { 
    @Override 
    public String toString() { 
     return "External SDCard was mounted"; 
    } 
    @Override 
    public int getCode() { 
     return 25; 
    } 
    }; 

    public abstract int getCode(); 

} 

如果每個值將被實施以同樣的方式,它更清晰做到這一點:

public enum EventAction { 
    SDCARD_MOUNTED(25, "External SDCard was mounted"); 
    private final int code; 
    private final String message; 
    private EventAction(int code, String message) { 
    this.code = code; 
    this.message = message; 
    } 
    @Override 
    public String toString() { return message; } 
    public int getCode() { return code; } 
} 
+0

大,清晰的例子。我以一種常見的方式實現了像你所展示的許多價值觀。 – Maxim 2011-12-13 18:04:06

5

您需要在申報的方法枚舉級別:

public enum EventAction 
{ 
    SDCARD_MOUNTED 
    { 
    public String toString() { 
     return "External SDCard was mounted"; 
    } 

    public int getCode() { 
     return 25; 
    } 
    }; 

    public abstract int getCode(); 

} 
3
public enum EventAction 
{ 
    SDCARD_MOUNTED("External SDCard was mounted",25), 
    SDCARD_MOUNTED_1("External SDCard was mounted 111111111",50); 

    private String details; 
    private int code; 

    private EventAction(String details,int code){ 
     this.code = code; 
     this.details = details; 
    } 

    public String toString() { 
     return this.details; 
    } 

    public int getCode() { 
     return this.code; 
    } 
} 

在主

System.out.println(EventAction.SDCARD_MOUNTED.toString()); 
System.out.println(EventAction.SDCARD_MOUNTED.getCode()); 

OUTPUT:

External SDCard was mounted 
25 
External SDCard was mounted 111111111 
50 
+0

這不允許其他枚舉值的不同屬性。 – erickson 2011-12-13 17:43:57

相關問題