1

I read java language specification here.Here it says

  1. An inner class is a nested class that is not explicitly or implicitly declared static.
  2. Inner classes include local, anonymous and non-static member classes.
  3. Inner classes may not declare static initializers or member interfaces, or a compile-time error occurs.
  4. Inner classes may not declare static members, unless they are constant variables, or a compile-time error occurs.

But my question is why inner/nested class can not have static members & why a compile-time error occur? * I'm new in Java

Maico
  • 21
  • 3

1 Answers1

1

Simply put, inner/nested classes cannot have static members, because in order to access them you would need an instance of the nested class, which breaks the staticness.

Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
  • 2
    That's not a really good justification... You need an enclosing instance to *create an instance of an inner class*. You don't need it to *refer to the class*. There was nothing forcing the Java designers to prevent static members of inner classes, it was purely a *choice*. – Marko Topolnik Jan 20 '14 at 12:21
  • 1
    And the choice does make sense because there is no good point of placing the static members inside inner classes. The enclosing class is just as good a place for them. – Marko Topolnik Jan 20 '14 at 12:22
  • Finally, there are such inner classes which do not require enclosing instances. – Marko Topolnik Jan 20 '14 at 12:22