问题描述
我试图在Java中声明一个枚举,并在switch语句中使用该类型的变量,其中涵盖了该类型的枚举常量的所有可能情况。
I'm trying to declare an enum in Java and use a variable of that type in a switch statement, where all possible cases for enum constants of that type are covered.
enum MyEnum {
FOO,
BAR
}
private static void test(MyEnum e) {
String msg;
switch (e) {
case FOO:
msg = "foo";
break;
case BAR:
msg = "bar";
break;
}
System.out.println("Enum is: " + e + " msg is: " + msg); //compiler error
}
为什么编译器无法检测到此开关将总是初始化 msg
(或抛出NullPointerException,因为 e
为 null
)?
Why is the compiler not capable of detecting that this switch will always initialize msg
(or throw a NullPointerException because e
is null
)?
推荐答案
想象一下 MyEnum
是一个单独的类。这样就可以重新编译 MyEnum
类,并添加新值,而无需重新编译 EnumSwitchTest
(这样就不会得到任何错误)。
Imagine if MyEnum
was a separate class. Then it would be possible to recompile the MyEnum
class, and add new values, without recompiling EnumSwitchTest
(so not getting any errors).
然后,另一个类就有可能使用新值调用 test
。
Then it would be possible for another class to call test
with the new value.
这篇关于为什么在switch语句中有每个枚举常量的用例时,为什么仍必须提供默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!