Instantiating static nested classes

219 Views Asked by At

This class

public class Main {

    public static void main(String[] args) {
        Main m = new Main();
        m.new A();
        m.new B();    //1 - compilation error

        new Main.B();
    }

    class A{}
    static class B{}  //2
}

will result in a compile time error at line 1:

Illegal enclosing instance specification for type Main.B

But I cannot understand why, I find it a bit counterintuitive: at line 2 we have a static class definition, shouldn'it be accessible from object m as well?

Edit

If Main had a static variable i, m.i wouldn't result in a compilation error. Why is the behaviour different with class definition?

2

There are 2 best solutions below

6
SLaks On BEST ANSWER

No.

The whole point of a static inner class is that it doesn't have an instance of the enclosing class.

1
Aniket Thakur On

m.new B(); is incorrect way of instantiating a nested static class as B is not an instance variable of class Main - so does not need instance of Main to create it. Rather you can do

new Main.B();

Quoting from docs for clarity

A static nested class interacts with the instance members of its outer class (and other classes) just like any other top-level class. In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience.