Reputation: 173
Can I squeeze this functionality into the enum? I would also like to use the enum in a switch statement in another file. I would also like to make things private if possible. I know you can do a lot more to enums in java but the literature is a little confusing.
public static class SCENE {
public enum scene {
MENU,
PLAY
}
public static scene current = scene.MENU;
public static void switchToMenu() {
current = scene.MENU;
}
public static void switchToPlay() {
current = scene.PLAY;
}
};
Upvotes: 2
Views: 63
Reputation:
Enum Classes (enum
) are like a normal Classes, but restricted:
clone
;Enum<E>
;abstract
Despite of that (and some points I forgot), everything that can be done with a normal class, can be done with an enum
: use all kind of fields and methods. Even each Enum Constant can have its own fields or methods.
BUT, as already commented, not everything is meaningful or recommended - like having a state, non-final
fields.
public class Scene {
public enum Type { // maybe SceneType?
MENU,
PLAY;
private void switchTo() { // instance method, just an example
current = this; // bad example, should not change `Scene`'s state
}
}
public static Type current = Type.MENU;
public static void switchTo(Type type) {
Objects.requireNonNull(type);
current = type;
/* alternative, to show switch usage
switch (type) {
case PLAY:
current = Type.PLAY;
break;
case MENU:
...
*/
}
// just for demonstration, not the best solution
public static void switchToMenu() {
Type.MENU.switchTo();
}
public static void switchToPlay() {
Type.PLAY.switchTo();
}
}
not tested, no IDE was harmed (used), minor errors left for the user to solve
I do recommend, for above simple case, to only use the switchTo(Type)
method in Scene
; not the switchTo()
in Type
- added just as an example of what can be done. The Type.switchTo()
method is strange, it is accessing a field of Scene
, that is being more than just a type, wrong place for such functionality.
Obs: since Enum Classes work like normal classes, they can also be declared in an own file. But for the posted code, since bound to Scene
, it can stay as a nested enum - must be accessed like Scene.Type.PLAY
from other classes. (Your SCENE looks like being nested itself - static
keyword not allowed on top level class - so the real path would be even longer, likeSomeClass.Scene.Type.PLAY
)
Links:
Upvotes: 2
Reputation: 1606
you can do like this using current
as string
public enum Scene {
MENU ("MENU"),
PLAY ("PLAY");
private final String current;
private Scene (String current) {
this.current = current;
}
}
Upvotes: 0