1

we know that Static contexts can't reference any instance of any type, but what happens with main method, how the following code sample compiles with no problem:

public class MyOuter
{
    public static void main(String[] args) 
    {
        MyOuter mo = new MyOuter(); // gotta get an instance!
        MyOuter.MyInner inner = mo.new MyInner();
        inner.seeOuter();

        //Or

        MyOuter.MyInner inner = new MyOuter().new MyInner();
    } 

    class MyInner
    {
        public void seeOuter(){}
    }
 }

isn't it forbidden to instantiate an inner class from within a static context in it's enclosing class?

Azodious
  • 13,752
  • 1
  • 36
  • 71
Eslam Hamdy
  • 7,126
  • 27
  • 105
  • 165

1 Answers1

5

isn't it forbidden to instantiate an inner class from within a static context in it's enclosing class?

No - it's forbidden to instantiate an inner class without an instance of the enclosing class. In your case, you do have an instance of the enclosing class:

new MyOuter().new MyInner();

That's entirely fine.

The only reason you can normally get away without specifying the enclosing class from an instance method is that it's equivalent to

// Within an instance method
this.new MyInner();

See section 15.9.2 of the JLS for more details. Your constructor call is a "qualified class instance creation expression".

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194