Java Access Enum specific methods?

谁说胖子不能爱 提交于 2019-12-10 23:57:16

问题


I have created an enum as so:

enum Types { hi, hello, bye }

I have added a getter inside each individual enum as so:

enum Types {
    hi {
        String test = "From hi";
        public String getString() {
        return test;
    },
    etc.
}

Except I cannot call "Types.hi.getString()". Is there any way to do this? Thanks!


回答1:


In your enum class, define the method you want to access as public abstract.

Like so:

 enum Types {
      hi {
        public String getString() {
          return "From hi";
        }
      };

      public abstract String getString();
  }

As an alternative, let your enum class implement an interface:

public interface StringProvider {
     String getString();
}

public enum Types implements StringProvider {
  ...
}



回答2:


Method and field declarations should go inside the enum (i.e. Types). hi, bye and hello are instances of Types.




回答3:


You're not doing it exactly right.
Sun has a doc on how to include methods and fields in enums. Here it is.



来源:https://stackoverflow.com/questions/10055848/java-access-enum-specific-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!