I have a enum type class:
public enum Operation {
PLUS() {
@Override
double apply(double x, double y) {
// ERROR: Cannot make a static reference
// to the non-static method printMe()...
printMe(x);
return x + y;
}
};
private void printMe(double val) {
System.out.println("val = " + val);
}
abstract double apply(double x, double y);
}
As you see above, I have defined one enum
type which has value PLUS
. It contains a constant-specific body. In its body, I tried to call printMe(val);
, but I got the compilation error:
Cannot make a static reference to the non-static method printMe().
Why do I get this error? I mean I am overriding an abstract method in PLUS
body. Why is it in static
scope? How to get rid of it?
I know adding a static
keyword on printMe(){...}
solves the problem, but I am interested to know if there is another way if I want to keep printMe()
non-static?
Another issue, quite similar as above one, but this time the error message sounds the other way around, i.e. PLUS(){...}
has non-static context:
public enum Operation {
PLUS() {
// ERROR: the field "name" can not be declared static
// in a non-static inner type.
protected static String name = "someone";
@Override
double apply(double x, double y) {
return x + y;
}
};
abstract double apply(double x, double y);
}
I try to declare a PLUS
-specific static
variable, but I end up with error:
the field "name" can not be declared static in a non-static inner type.
Why can I not define static constant inside PLUS
if PLUS
is an anonymous class? The two error messages sound contradictory to each other, as the 1st error message says PLUS(){...}
has static context while the 2nd error message says PLUS(){...}
has non-static context. I am even more confused now.