admin管理员组

文章数量:1433520

Consider the following excerpt from JLS: §15.9.2. Determining Enclosing Instances

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

The applicable code that I can think of - what the clause is trying to say is following:

class Outer {
    void instanceMethod() {
        class LocalNonStaticContext {
            void print() {
                System.out.println("Has enclosing instance of Outer.");
            }
        }
        new LocalNonStaticContext().print(); // Valid because we're in a non-static context.
    }

    static void staticMethod() {
        // Compile-time error: LocalNonStaticContext requires an enclosing instance.
        // new LocalNonStaticContext();
    }
}
  • But this seems too naive - as it is understood that scope of a local class is limited to method in which it is declared - hence it is not possible to invoke it from any other method.

What can be the scenario that this clause is trying to call out - for the Compilation error to take place - that it is trying to prevent?

本文标签: javaLocal Class instance creation expression occurs in a static contextcompilation errorStack Overflow