views:

103

answers:

1

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

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

+4  A: 

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.

polygenelubricants