简体   繁体   中英

java enum access issue by variable

I see a weird situation and wonder if I missed something. I have one class define an enum like this

public class Foo {
  public enum Day { Monday, Tuesday, ...};
  ...
}

Then in another class I have

public class Bar {
    Foo aFoo=new Foo();

    void test(){
       System.out.println(Foo.Day.Monday);  // ok
       System.out.println(aFoo.Day.Monday);  // complie error Day not accessible
    }
}

Anyone have an explanation for this? Thanks.

The reason is that when you have an expression like Q.Id and Q is an expression of type T (Q is your aFoo and T = Foo ):

If there is not exactly one accessible (§6.6) member of the type T that is a field named Id , then a compile-time error occurs.

In other words you can reference a static field with an instance ( aFoo.someStaticVariable ) but not a nested class.

So you need to use Outerclass.Nestedclass to access it.

From the JLS §8.9 :

Nested enum types are implicitly static . It is permissible to explicitly declare a nested enum type to be static .

Hence it makes no sense to access Day through a Foo instance; it can only be accessed through the Foo class itself as in your first print statement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM