The JLS 15.9.2 tells us how to determine an enclosing instance: Let C be the class being instantiated, and let i be the instance being created.
If C is an inner class, then i may have an immediately enclosing instance (§8.1.3), determined as follows:
[...]
If C is a local class, then:
If C occurs in a static context, then i has no immediately enclosing instance.
Otherwise, if the class instance creation expression occurs in a static context, then a compile-time error occurs.
Otherwise, let O be the immediately enclosing class of C. Let n be an integer such that O is the n'th lexically enclosing type declaration of the class in which the class instance creation expression appears.
The immediately enclosing instance of i is the n'th lexically enclosing instance of this.
I didn't get what the bolded case means. Let me provide the example I wasn't supposed to be compiled:
class A{
int a;
public static void main (String[] args) throws java.lang.Exception{
class Foo{
void bar(){
}
}
Foo f = new Foo(); //Instance creation expression occured in the static context
}
}
What's wrong with that? Couldn't you provide an actual example describing the second point?