Why can we have static final members but cant have static method in an inner class?

╄→尐↘猪︶ㄣ 提交于 2020-01-21 04:45:11

问题


Why can we have static final members but cant have static method in an non static inner class ?

Can we access static final member variables of inner class outside the outer class without instantiating inner class ?


回答1:


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

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

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.


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.



来源:https://stackoverflow.com/questions/2482327/why-can-we-have-static-final-members-but-cant-have-static-method-in-an-inner-cla

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!