[英]Why can we have static final members but cant have static method in an inner class?
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 ): 但是,确切地说,根据JLS术语( 8.1.3 ),
Inner
被称为嵌套类:
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.
不是内部类的嵌套类可以根据Java编程语言的通常规则自由地声明静态成员。
Also, it's NOT exactly true that an inner class can have static final
members; 而且,内部类可以拥有
static final
成员并不完全正确; 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. 在此上下文中允许编译时常量的原因显而易见:它们在编译时内联。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.