为什么我们可以拥有静态最终成员但是在内部类中不能使用静态方法?

Ash*_*ish 7 java static-members inner-classes

为什么我们可以拥有静态最终成员但不能在非静态内部类中使用静态方法?

我们可以访问外部类之外的内部类的静态最终成员变量而无需实例化内部类吗?

pol*_*nts 7

您可以在静态 "内部"类中使用静态方法.

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!"
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,Inner根据JLS术语(8.1.3),确切地说,它被称为嵌套类:

内部类可以继承非编译时常量的静态成员,即使它们可能不会声明它们.不是内部类的嵌套类可以根据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!
    }
}
Run Code Online (Sandbox Code Playgroud)

在此上下文中允许编译时常量的原因显而易见:它们在编译时内联.