我可以在Java枚举中添加一个返回方法吗?

时间:2011-12-13 17:18:54

标签: java android enums

这样可以在Android中使用Enum吗?

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

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

从外部代码我只能访问EventAction.SDCARD_MOUNTED.toString(),但.getCode()不可见。我看到的示例显示了如何从代码内部使用getCode()。

3 个答案:

答案 0 :(得分:9)

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; }
}

答案 1 :(得分:5)

您需要在枚举级别声明方法:

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

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

  public abstract int getCode();

}

答案 2 :(得分: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());

输出:

External SDCard was mounted
25
External SDCard was mounted 111111111
50