案例一
class Outer {
void outerMethod() {
Inner i = new Inner(); //compile error : cannot find symbol
i.innerMethod();
class Inner {
void innerMethod() {
System.out.println("inner class method...");
}
}
}
}
案例二
class Outer {
void outerMethod() {
Inner i = new Inner();
i.innerMethod();
}
class Inner {
void innerMethod() {
System.out.println("inner class method...");
}
}
}
这两种情况下有两个独立的类文件。但一个出现编译错误,另一个正常。这是什么原因?
最佳答案
Local classes有不同的范围规则。 来自JLS, section 6.3 :
"The scope of a local class declaration immediately enclosed by a block (§14.2) is the rest of the immediately enclosing block, including its own class declaration. "
在你的第一个例子中,你在这个内部类的范围之前调用了内部类的构造函数,因此这是非法的。
在您的代码中说明这一点:
void outerMethod() {
// ...
// ...
// Beginning of legal usage scope of the local class
class Inner {
void innerMethod() {
System.out.println("inner class method...");
}
}
// ...
// ...
// End of legal usage scope of the local class
}
关于java - 创建局部内部类的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22931447/