为什么我们可以在非静态内部类中拥有静态最终成员但不能拥有静态方法?
我们可以在外部类之外访问内部类的 static Final 成员变量而不实例化内部类吗?
您可以在 a 中使用静态方法static“内”类。
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!"
}
}
然而,准确地说,Inner
根据 JLS 术语,称为嵌套类 (8.1.3):
内部类可以继承不是编译时常量的静态成员,即使它们可能没有声明它们。不是内部类的嵌套类可以根据 Java 编程语言的通常规则自由声明静态成员。
还有,它是NOT内部类可以具有完全正确的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!
}
}
在这种情况下允许编译时常量的原因很明显:它们在编译时内联。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)