2

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?

Luigi Cortese
  • 10,841
  • 6
  • 37
  • 48

2 Answers2

2

No.

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

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
1

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.

Aniket Thakur
  • 66,731
  • 38
  • 279
  • 289
  • Only non static nested classes need outer class for its instantiation. So saying `m.new B();` is not correct as `m` does not own `B` it is like any other top level class. So what you mean is why can't I access the class as `m.B` like any other static variable. I may not be the correct person to answer that :) this is how it was designed. – Aniket Thakur Dec 20 '15 at 14:53