Home > Net >  illegal to access static member while in an enum constructor
illegal to access static member while in an enum constructor

Time:01-30

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:

  1. Enums in Java can have fields and constructor, see displayString field and the one argument constructor.
  2. 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

  •  Tags:  
  • Related