Why can we have static final members but cant have static method in an non static inner class ?
Can we access static final member variables of inner class outside the开发者_开发百科 outer class without instantiating inner class ?
YOU CAN have static method in a static "inner" class.
public class Outer {
static String world() {
return "world!";
}
static class Inner {
static String helloWorld() {
return "Hello " + Outer.world();
}
}
public static void main(String args[]) {
System.out.println(Outer.Inner.helloWorld());
// prints "Hello world!"
}
}
To be precise, however, Inner
is called a nested class according to JLS terminology (8.1.3):
Inner classes may inherit static members that are not compile-time constants even though they may not declare them. Nested classes that are not inner classes may declare static members freely, in accordance with the usual rules of the Java programming language.
Also, it's NOT exactly true that an inner class can have static final
members; to be more precise, they also have to be compile-time constants. The following example illustrates the difference:
public class InnerStaticFinal {
class InnerWithConstant {
static final int n = 0;
// OKAY! Compile-time constant!
}
class InnerWithNotConstant {
static final Integer n = 0;
// DOESN'T COMPILE! Not a constant!
}
}
The reason why compile-time constants are allowed in this context is obvious: they are inlined at compile time.
精彩评论