8

How come this code doesnt 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 the Enum inside class A, everything is okay.

This is quite surprising. I dont think I have this problem in C++.

sivabudh
  • 31,807
  • 63
  • 162
  • 228

1 Answers1

12

You can fix this by making B static:

static class B { ...

This mirrors more closely what C++ does with nested classes. By default (without static), instances of B contain a hidden reference to an instance of A.

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

Community
  • 1
  • 1
Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
  • 8
    An enum is an intrinsically static beast. In the example above, you only ever want there to be one Enum.AD object. But if you declared an enum inside a non-static class, you'd (in theory) need a different instance of Enum.AD for each synamic scope. That doesn't make sense ... therefore it is forbidden. – Stephen C Nov 04 '09 at 06:59