MrDrProfessorTyler
MrDrProfessorTyler

Reputation: 423

Java Access Enum specific methods?

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!

Upvotes: 2

Views: 3786

Answers (3)

Urs Reupke
Urs Reupke

Reputation: 6921

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 {
  ...
}

Upvotes: 8

Bhesh Gurung
Bhesh Gurung

Reputation: 51030

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

Upvotes: 0

user1241335
user1241335

Reputation:

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

Upvotes: -1

Related Questions