3

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.

1

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. It explains why, but I don't understand your "By the way" part.
It is a side note but it is not the reason for the behaviour: in someInstance.f, f must be a field, whether static or not - f can't be a class name. I have edited for clarity.
Your enum is static by default (see link in answer), that means it's the same for all instances of Foo. So it's not really useful to access it via the instance but it is useful to access it via the class itself. That's the basic idea.
3

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.

3 Comments

all other statics can be accessed by instances. why not enum?
Accessing static fields through class instances is evil. Maybe Java designers realized that and didn't want to add more sulphur to the open wound. :)
@user3097579 Not static nested classes, which a nested enum is.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.