Java: why is this not compiling?

How does this code not compile?

class A { class B { public enum Enum <-- this line { AD, BC } } } 

Compiler Reports:

 enum declarations allowed only in static contexts. 

But then when I put Enum inside class A, everything is fine.

This is pretty amazing. I don't think I have this problem in C ++.

+6
java enums
source share
1 answer

You can fix this by setting B static:

 static class B { ... 

This more accurately reflects what C ++ does with nested classes. By default (without static ), instances of B contain a hidden link to instance A.

A good explanation of the differences can be found in the Java inner class and the static nested class .

+10
source share

All Articles