0

Why can't I add constant of other class into a switch statement in java?

example: I have a class

public class Game {


    static class GameMode {
        public static final GameMode SURVIVAL = new GameMode();
        public static final GameMode ADVENTURE = new GameMode();
        public static final GameMode GOD = new GameMode();
    }

    GameMode CurrentMode = GameMode.GOD;

}

but when I define a switch statement, It give me an error:

    void OnGame(){
        switch (CurrentMode){
            case GameMode.GOD: // case expressions must be constant expressionsJava(536871065)
                System.out.println("Player On God Mode");
                break;
            case GameMode.SURVIVAL: // case expressions must be constant expressionsJava(536871065)
                System.out.println("Player On Survival Mode");
                break;
            case GameMode.ADVENTURE: // case expressions must be constant expressionsJava(536871065)
                System.out.println("Player On Adventure Mode");
                break;


        }
    }

That makes me confused. SURVIVAL, ADVENTURE and GOD mode are all constant, I add "final" in front of it, why can't I use it in switch statement?

Here are some image: enter image description here enter image description here enter image description here

Cflowe Visit
  • 331
  • 1
  • 4
  • 12

1 Answers1

2

According to Java Language Specification (JLS):

A case label has one or more case constants. Every case constant must be either a constant expression (§15.29) or the name of an enum constant (§8.9.1), or a compile-time error occurs.

Your case is obviously not an enum constant, so I guess you are trying to use a constant expression but your GameMode class does not qualify as a constant expression.

A constant expression is an expression denoting a value of primitive type or a String that does not complete abruptly and is composed using only the following...

Tasos P.
  • 3,994
  • 2
  • 21
  • 41
  • So that means I can only use Primitive type / String, and I cannot use other object in switch statement? – Cflowe Visit Apr 17 '22 at 18:42
  • Yes, with the exception of enum. Enum can be used and since they can be customized to an extent, it's a perfect solution – Tasos P. Apr 17 '22 at 18:44