Home > Java > javaTutorial > Why Doesn't My Java Switch Statement Accept Static Constants from an Abstract Class?

Why Doesn't My Java Switch Statement Accept Static Constants from an Abstract Class?

Patricia Arquette
Release: 2024-12-19 21:29:13
Original
888 people have browsed it

Why Doesn't My Java Switch Statement Accept Static Constants from an Abstract Class?

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;
    ...
}
Copy after login

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
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template