Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: how come this does not compile?

Tags:

java

enums

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++.

like image 487
sivabudh Avatar asked Nov 04 '09 06:11

sivabudh


1 Answers

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.

like image 198
Greg Hewgill Avatar answered Oct 13 '22 19:10

Greg Hewgill