Reputation: 423
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
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
Reputation: 51030
Method and field declarations should go inside the enum (i.e. Types). hi, bye and hello are instances of Types.
Upvotes: 0
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