且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-12-24 09:26:15

你可以在静态内部类中使用静态方法。

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!"
    }
}

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

To be precise, however, Inner is called a nested class according to JLS terminology (8.1.3):


内部类可以继承不编译的静态成员 - 时间常数,即使他们可能不会声明它们。不是内部类的嵌套类可以根据Java编程语言的通常规则***地声明静态成员。

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.






此外,它的 NOT 完全正确,内部类可以有静态最终成员;更确切地说,它们还必须是编译时常量。以下示例说明了区别:


Also, it's NOT exactly true that an inner class can have static final members; 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.