4

I have a doubt in using Inner Classes in java. Here is my code.

Code:

public class Test{

      public class InnerClass{
             public static int num = 10;
      }       

}

It's not allowed. I got the error message "The field num cannot be declared static; static fields can only be declared in static or top level types".

public class Test{

      public class InnerClass{
             public static final int num = 10;
      }       

}

But It's allowed. I have not declared InnerClass as static and top level element but how it works?

kannanrbk
  • 6,964
  • 13
  • 53
  • 94

1 Answers1

8

To quote from the linked answer.

8.1.2 Inner Classes and Enclosing Instances
...
Inner classes may not declare static members, unless they are compile-time constant fields (§15.28).

final makes them constant once initialized, = 10 is a compile time constant value. Thus it is allowed.

Karthik T
  • 31,456
  • 5
  • 68
  • 87