Here's what I've written:
public class JavaApplication4 {
private RunMode runMode;
private enum RunMode {
STOP, START, SCE, SIE;
void reset() {
this = STOP; // <=== 'cannot assign a value to final variable this.'
}
}
}
As not开发者_StackOverflowed, the assignment to 'this' is flagged. Why is 'this' final, and how can I change the value of an enum variable with an enum instance method?
It really doesnt make sense to reassign an already instantiated Enum. Think of Enums as singleton objects. In your case, START, STOP, SCE and SIE are all singleton objects that are pre-instantiated. All you do is pass around their reference in your application.
The enum exists to provide you with a set of related constants that are used to describe some state (in your case, the run mode of the application). The instances are immutable, for good reason: they are supposed to represent constants.
You don't really want to "reset" the object that represents a run mode. You want to reset the run mode of the application. So the functionality belongs in the application class, and it is implemented by assigning a different enum object to the field.
public class JavaApplication4 {
private RunMode runMode;
public void reset() {
runMode = RunMode.STOP;
}
private enum RunMode {
STOP, START, SCE, SIE;
}
}
You can never change the value of an enum from one to another. Enums are meant to be constants. It sounds like you should probably return STOP
from the reset()
method (and any other potentially-state-changing methods) and write:
runMode = runMode.reset(); // etc
It's important to understand that enums are reference types, and meant to effectively be a collection of constant values. Not only can you not mutate one value into another, but you shouldn't change the value of any fields within the enum either (unless it's for caching).
Enums are just a bunch of constants grouped together under one type.
Is that what you want:
private RunMode runMode;
private enum RunMode {
STOP, START, SCE, SIE;
}
void reset() {
runMode = RunMode.STOP;
}
this
is not a modifiable entity. Easiest way is to move your reset()
inside the class
body itself:
public class JavaApplication4 {
private RunMode runmode;
private enum RunMode {
STOP, START, SCE, SIE;
}
void reset() { // <---- move it here
runMode = RunMode.STOP; // <=== ok
}
}
精彩评论