声明为内部 类 时 switch 语句中枚举值的行为
behaviour of enum values in switch statements when declared as inner classes
我知道这是一个微不足道的问题,但这让我很感兴趣;
因为内部 classes'(非静态)成员即使在外部 class、
中也不能在没有实例的情况下直接访问
而要访问静态常量,您必须使用外部 class hai.x 范围;
但在 "use of enums switch as case constants" 的情况下似乎是相反的; 看dostuff2()
case RED: works but case value.RED gives error an enum switch case label must be the unqualified name of an enumeration constant
我知道上面的说法说明了一切;我只是好奇
如果我们假设编译器将 'value. ' 填充到所有开关常量..
为什么枚举的正常声明也不是这种情况 value v=RED
public class enumvalues
{
public enum values
{
RED,GREEN,VALUE
}
public class hai
{
static final int x=90;
}
public static class statichai
{
}
public static void main(String []args)
{
}
public void dostuff2(values v)
{
// v =RED this is illegal
// System.out.println(RED); this will not compile because it cannot be accessed directly
// System.out.println(x); this will not compile because it cannot be accessed directly
switch(v)
{
case RED: //use of value.RED is strictly forbidden
System.out.println("red");
}
}
}
因为它需要为枚举创建特殊情况以供检查。
考虑另一个例子
interface SomeInterface{}
enum Values implements SomeInterface {RED};
enum MoreValues implements SomeInterface {RED};
public void dostuff2(SomeInterface value)
{
value = RED;
}
和你的代码很像,dostuff2
完全一样。因为编译器枚举的底层只是常规 类。
因此,为了处理您的示例,您需要添加特殊情况来处理枚举。
我知道这是一个微不足道的问题,但这让我很感兴趣;
因为内部 classes'(非静态)成员即使在外部 class、
中也不能在没有实例的情况下直接访问而要访问静态常量,您必须使用外部 class hai.x 范围; 但在 "use of enums switch as case constants" 的情况下似乎是相反的; 看dostuff2()
case RED: works but case value.RED gives error an enum switch case label must be the unqualified name of an enumeration constant
我知道上面的说法说明了一切;我只是好奇
如果我们假设编译器将 'value. ' 填充到所有开关常量.. 为什么枚举的正常声明也不是这种情况 value v=RED
public class enumvalues
{
public enum values
{
RED,GREEN,VALUE
}
public class hai
{
static final int x=90;
}
public static class statichai
{
}
public static void main(String []args)
{
}
public void dostuff2(values v)
{
// v =RED this is illegal
// System.out.println(RED); this will not compile because it cannot be accessed directly
// System.out.println(x); this will not compile because it cannot be accessed directly
switch(v)
{
case RED: //use of value.RED is strictly forbidden
System.out.println("red");
}
}
}
因为它需要为枚举创建特殊情况以供检查。 考虑另一个例子
interface SomeInterface{}
enum Values implements SomeInterface {RED};
enum MoreValues implements SomeInterface {RED};
public void dostuff2(SomeInterface value)
{
value = RED;
}
和你的代码很像,dostuff2
完全一样。因为编译器枚举的底层只是常规 类。
因此,为了处理您的示例,您需要添加特殊情况来处理枚举。