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 ?
Inner Classes As with instance methods and variables, an inner class is associated with an instance of its enclosing class and has direct access to that object's methods and fields. Also, because an inner class is associated with an instance, it cannot define any static members itself.
Although it is enclosed, a static member class cannot access the enclosing class's instance fields and invoke its instance methods. However, it can access the enclosing class's static fields and invoke its static methods, even those members that are declared private .
InnerClass cannot have static members because it belongs to an instance (of OuterClass ). If you declare InnerClass as static to detach it from the instance, your code will compile.
Static classes are sealed and therefore cannot be inherited. They cannot inherit from any class except Object. Static classes cannot contain an instance constructor.
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.
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