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?

0

1 Answer 1

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".

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.