2

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
  • 1
    Is this your code, seems to have a missing } Commented Apr 7, 2012 at 15:48

3 Answers 3

8

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 {
  ...
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.