![](/img/trans.png)
[英]Why can't we have static method in a (non-static) inner class (pre-Java 16)?
[英]Why can we have static final members but cant have static method in an 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!"
}
}
但是,确切地说,根据JLS术语( 8.1.3 ), Inner
被称为嵌套类:
内部类可以继承非编译时常量的静态成员,即使它们可能不会声明它们。 不是内部类的嵌套类可以根据Java编程语言的通常规则自由地声明静态成员。
而且,内部类可以拥有static final
成员并不完全正确; 更确切地说,它们也必须是编译时常量 。 以下示例说明了不同之处:
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!
}
}
在此上下文中允许编译时常量的原因显而易见:它们在编译时内联。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.