Why is this int switch valid:
public class Foo {
private final static int ONE = 1;
private final static int TWO = 2;
public static void main(String[] args) {
int value = 1;
switch (value) {
case ONE: break;
case TWO: break;
}
}
}
While this enum switch is not:
import java.lang.annotation.RetentionPolicy;
public class Foo {
private final static RetentionPolicy RT = RetentionPolicy.RUNTIME;
private final static RetentionPolicy SRC = RetentionPolicy.SOURCE;
public static void main(String[] args) {
RetentionPolicy value = RetentionPolicy.RUNTIME;
switch (value) {
case RT: break;
case SRC: break;
}
}
}
I know that what goes in the case must be a constant, so why can I use a "final static int" as constant but not a "final static <your enum>"?
The static keyword means the value is the same for every instance of the class. The final keyword means once the variable is assigned a value it can never be changed.
Static variables are normally declared as constants using the final keyword. Constants are variables that are declared as public/private, final, and static. Constant variables never change from their initial value.
Declaring variables only as static can lead to change in their values by one or more instances of a class in which it is declared. Declaring them as static final will help you to create a CONSTANT. Only one copy of variable exists which can't be reinitialize.
Static is used to define the class member that can be used independently of any object of the class. Final is used to declare a constant variable or a method that cannot be overridden or a class that cannot be inherited. This is the main difference between static and final.
Because a case statement label must have either a compile time constant or an EnumConstantName. JLS 14.11
Compile time constants can only be strings and primitive types, as described by JLS 15.28. Thus you can not use a static final <your enum>, as it is neither a compile time constant, nor the name of an enum.
The case argument must be primitive; it cannot be an object.
However, you can use enums as follows:
RetentionPolicy value = ...
switch (value) {
case RUNTIME:
case SOURCE:
}
Because value
is declared to be of type RetentionPolicy
you can use the enum constants directly inside the switch.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With