Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ?

like image 724
Ashish Avatar asked Mar 20 '10 07:03

Ashish


People also ask

Why can't inner classes have static members?

Inner Classes As with instance methods and variables, an inner class is associated with an instance of its enclosing class and has direct access to that object's methods and fields. Also, because an inner class is associated with an instance, it cannot define any static members itself.

Can static inner class have static method?

Although it is enclosed, a static member class cannot access the enclosing class's instance fields and invoke its instance methods. However, it can access the enclosing class's static fields and invoke its static methods, even those members that are declared private .

Can we have static variable in inner class?

InnerClass cannot have static members because it belongs to an instance (of OuterClass ). If you declare InnerClass as static to detach it from the instance, your code will compile.

Why we Cannot inherit static method?

Static classes are sealed and therefore cannot be inherited. They cannot inherit from any class except Object. Static classes cannot contain an instance constructor.


1 Answers

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.

like image 112
polygenelubricants Avatar answered Oct 10 '22 23:10

polygenelubricants