Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are "static final" fields allowed in inner classes?

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?

like image 690
kannanrbk Avatar asked Feb 18 '23 14:02

kannanrbk


1 Answers

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.

like image 184
Karthik T Avatar answered Mar 04 '23 23:03

Karthik T