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?
版权声明:本文标题:java - Local Class instance creation expression occurs in a static context - compilation error? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745587756a2665011.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论