声明为内部类时,switch语句中枚举值的行为

时间:2016-06-21 10:27:29

标签: java enums constants inner-classes

我知道这是一个微不足道的问题,但这对我来说非常有趣;

由于内部类(非静态)成员即使在外部类中也无法直接访问它,

并且在访问静态常量时,你必须使用外部类hai.x; 但在“使用枚举开关作为案例常量”的情况下,它似乎是另一种方式; 看看dostuff2()

  

案例RED:有效但案例值.RED给出错误枚举开关案例标签必须是枚举常量的非限定名称

我知道上面的陈述说明了一切;我只是好奇

如果我们假设编译器填充'值'。 '到所有开关常量.. 为什么这不是枚举的正常声明的情况,以及值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");
        }
    }
}

1 个答案:

答案 0 :(得分:1)

因为它需要为枚举创建特殊情况以供检查。 考虑另一个例子

interface SomeInterface{}
enum Values implements SomeInterface {RED};
enum MoreValues implements SomeInterface {RED};

public  void dostuff2(SomeInterface value)
{
value = RED;
}

它与您的代码非常相似,dostuff2完全相同。对于编译器枚举而言,它只是常规类。 因此,为了处理您的示例,您需要添加特殊情况来处理枚举。