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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With