java – 为什么我们可以拥有静态最终成员但是在内部类中不能使用
发布时间:2020-12-15 03:03:47 所属栏目:Java 来源:网络整理
导读:为什么我们可以拥有静态最终成员但是在非静态内部类中不能使用静态方法? 我们可以访问外部类之外的内部类的静态最终成员变量而无需实例化内部类吗? 解决方法 您可以在静态“内部”类中使用静态方法. public class Outer { static String world() { return
为什么我们可以拥有静态最终成员但是在非静态内部类中不能使用静态方法?
我们可以访问外部类之外的内部类的静态最终成员变量而无需实例化内部类吗? 解决方法
您可以在静态“内部”类中使用静态方法.
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被称为嵌套类:
而且,内部类可以拥有静态最终成员并不完全正确;更确切地说,它们也必须是编译时常量.以下示例说明了不同之处: 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! } } 在此上下文中允许编译时常量的原因显而易见:它们在编译时内联. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |