manifold
manifold

Reputation: 437

behaviour of enum values in switch statements when declared as inner classes

i know this is trivial question but this is totally intriguing me;

As inner classes' (non-static) members cannot be directly accessed without instance of it even in outer class,

and while to access static constants u have to scope with outer class hai.x ; but in the case of "use of enums switch as case constants" it seems to be other way around; look dostuff2()

case RED: works but case value.RED gives error an enum switch case label must be the unqualified name of an enumeration constant

i know above statement says it all;i'm just curious

if we assume that compiler pads that 'value. ' to all switch constants.. why this isn't the case with normal declartion of enum as well 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");
        }
    }
}

Upvotes: 1

Views: 667

Answers (1)

user902383
user902383

Reputation: 8640

Because it would require to create special case for enums for check. consider another example

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

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

It is quite similar to your code to yours, and dostuff2 is exactly same. As under hood for compiler enums are just regular classes. So to handle your example, you needed to add special case to handle enums.

Upvotes: 2

Related Questions