[英]create a instance of local inner class
我是
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...");
}
}
}
在这两种情况下有两个单独的类文件。 但是一个是编译错误而另一个是好的。 这是什么原因?
“由一个块(第14.2节)直接包含的本地类声明的范围是直接封闭块的其余部分,包括它自己的类声明。”
在第一个示例中,您在此内部类的作用域之前调用Inner类的构造函数,因此它是非法的。
为了在您的代码中说明这一点:
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
}
您的案例II正在运作,因为您已经做了适当的范围界定
class Outer {
void outerMethod() {
Inner i = new Inner();
i.innerMethod();
} --> You have the scope change here in this case
class Inner {
void innerMethod() {
System.out.println("inner class method...");
}
}
}
即,必须在使用之前定义本地内部类。
在第一种情况下,当您实例化Inner类时,它是未知的,因此导致编译时错误
在案例1中,您必须先定义一个类然后再使用它。 这样做的原因是Inner
类的上下文。 考虑一下:
class Outer {
void outerMethod() {
Inner i = new Inner(); //compile error : cannot find symbol
i.innerMethod();
final int localVar = 1;
class Inner {
void innerMethod() {
System.out.println("inner class method... localVar = " + localVar );
}
}
Inner i = new Inner(); // No Error
i.innerMethod();
}
}
如您所见, Inner
类使用先前定义的局部变量,但稍后只能在代码中使用。
在你的第一种情况下,当你实例化你的Inner
类时,它是未知的。 只需更改说明的顺序:
void outerMethod() {
class Inner {
void innerMethod() {
System.out.println("inner class method...");
}
}
Inner i = new Inner();
i.innerMethod();
}
在使用之前必须使用该方法定义本地内部类。
试试这个:
class Outer {
void outerMethod() {
class Inner { // Inner class definition
void innerMethod() {
System.out.println("inner class method...");
}
}
Inner i = new Inner(); // No compilation error
i.innerMethod();
}
}
在案例1中 - 将类视为变量声明(因为它只存在于此方法的范围内),当您仍然不存在时,您尝试分配变量“inner”,将类声明移动到方法的顶部,它会编译。
class Outer {
void outerMethod() {
class Inner {
void innerMethod() {
System.out.println("inner class method...");
}
}
Inner i = new Inner();
i.innerMethod();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.