I have an enum and want to attach a static function to it that takes an argument of that enum's case and returns a different string dependent on some conditions. This is throwing a bunch of errors, though, including "No modifiers allowed for enum constants" and "it is illegal to access static member ... from enum constructor or instance initializer." How do I correctly attach a static function to an enum? Because of my context, this really does seem like the most sensible place to put it.
Example Code:
public enum Operation {
SUM,
SUBTRACT,
PRODUCT,
DIVIDE,
public String display(Operation operation) {
if (operation == this.SUM) {
return " ";
} else if (operation == this.SUBTRACT) {
return "-";
} else if (operation == this.DIVIDE) {
return "/";
} else {
return "*";
}
}
}
CodePudding user response:
This looks like your main problem:
public enum Operation {
SUM,
SUBTRACT,
PRODUCT,
DIVIDE,
That last comma should be a semicolon, to terminate the list of enum member constants.
You might have other issues (I didn't check), but start by fixing that syntax error.
CodePudding user response:
I think you should choose a different way to implement what you want to achieve:
public enum Operation {
SUM(" "),
SUBTRACT("-"),
PRODUCT("*"),
DIVIDE("/");
private final String displayString;
Operation(final String displayString) {
this.displayString = displayString;
}
public String getDisplayString() {
return displayString;
}
}
Few key points:
- Enums in Java can have fields and constructor, see
displayStringfield and the one argument constructor. - Enums in Java can have instance methods, in which you can use instance fields, like
getDisplayString
Then you can use it as follows:
final Operation sumOperation = Operation.SUM;
final Operation divideOperation = Operation.DIVIDE;
System.out.println("First operation: " sumOperation.getDisplayString()); // First operation:
System.out.println("Second operation: " divideOperation.getDisplayString()); // Second operation: /
I hope it helps, if you need further details please describe what more information you need in the comments
