Java Switch Statement: Troubleshooting Constant Expression Requirement
In the scenario presented, a switch statement attempts to match an integer constant with static constants defined in an abstract class. However, the compilation fails with a "constant expression required" error.
Understandably, compile-time constant expressions are necessary for switch statements. Yet, the Foo.BAR, Foo.BAZ, and Foo.BAM constants seem constant.
Why aren't these constants treated as compile-time constant expressions?
According to the Java Language Specification (JLS) §15.28, a compile-time constant expression consists of only certain primitive types and literals, excluding object references. In this case, Foo.BAR is not a compile-time constant expression because it refers to a static field, which is initialized at runtime, not compile-time.
Resolving the issue:
To resolve this issue, the Foo.BA* variables must be initialized with compile-time constant expressions:
public abstract class Foo { ... public static final int BAR = 1; public static final int BAZ = 2; public static final int BAM = 3; ... }
With these initializers, the compiler can determine the values of Foo.BA* at compile time, making them valid for use in a switch statement.
Alternative approach using enums:
Another option to ensure compile-time constant values is to use enums:
public enum FooConstants { BAR, BAZ, BAM }
However, using enums imposes additional restrictions, such as requiring a default case and prohibiting case labels that evaluate to expressions.
The above is the detailed content of Why Doesn't My Java Switch Statement Accept Static Constants from an Abstract Class?. For more information, please follow other related articles on the PHP Chinese website!