Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java enum can I add a return method?

Is it possible to use Enum in Android like this?

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

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

From the outside code I have an access only to EventAction.SDCARD_MOUNTED.toString() but .getCode() is not visible. Examples I saw show how getCode() is used from inside code.

like image 558
Maxim Avatar asked Dec 04 '22 06:12

Maxim


2 Answers

Declare getCode() as an abstract method:

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

  public abstract int getCode();

}

If every value is going to be implemented the same way, it's clearer to do this:

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; }
}
like image 96
erickson Avatar answered Dec 21 '22 10:12

erickson


You need declare the method at the enum level :

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

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

  public abstract int getCode();

}
like image 28
Olivier Croisier Avatar answered Dec 21 '22 10:12

Olivier Croisier