about non-static class in java
My doubt is when I r开发者_StackOverflow社区un the following program
public class NonStatic
{
class a
{
static int b;
}
}
The compiler is giving a error that "inner classes cannot have static declarations"
ok,then I made a change instead of "static int b" to "final static int b" its giving
same error but when I wrote "final static int b=10" means with initialization compiler
didn't complain,please can any body explain this what's the concept behind this.
it is so by design, just see the Java Language Specification: Inner Classes and Enclosing Instances
An inner class is a nested class that is not explicitly or implicitly declared static. [...] Inner classes may not declare static members, unless they are compile-time constant fields (§15.28).
final static int b=10
Is interpreted as a constant so compiler can just inline it. Similarly you can have static final constants in interface.
final static int b
Is missing initialization,which is required for final member, so compiler can't quite figure what you want.
Try putting following block right after it out of curiosity:
static {
b=10;
}
Although it probably would not work...
If a field is static, there is only one copy for the entire class, rather than one copy for each instance of the class
A final field is like a constant: once it has been given a value, it cannot be assigned to again. hence when we r using final we have to assign the value to the variable.
have a look at the following link
Here is my take on this issue.
- Inner class is defined as a not static member of outer class and hence, it's instance cannot exist without the instance of outer class.
- The static fields of a class are accessible without creating an instance of that class.
- Now if you add a static field in the inner class, that means you can access that field without create the instance of inner class BUT according to #1 instance of inner cannot exist without an instance of outer class. So this is the conflict and hence the error.
TO CROSSCHECK : Just declare the inner class static and it will correct the error.
Its because a final static variable is a constant meaning it can't change at run time, while a static variable is not a constant and can change during runtime.
So in a class static variables aren't allowed in an inner class but the constants(final) are allowed.
精彩评论