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?
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:
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
See section 15.9.2 of the JLS for more details. Your constructor call is a “qualified class instance creation expression”.