Search code examples
javaclassinner-classes

nested class has a static variable?


I know that nested class has not had static member,

class OuterClass {
     class InnerClass {
      private static int x = 0; // this is error
     }

}

But when we declared it with final

 class OuterClass {
     class InnerClass {
      private static final int x = 0; // ok
     }
}

is it related with the final keyword, because variable can't be changed anymore? Or is there another reason for this?


Solution

  • Because private static final int x = 0; is compile time constant. According java doc,

    Inner classes may not declare static members, unless they are compile-time constant fields