为什么这段代码甚至无法编译?
public class T {
public static void main(String[] args) {
class A extends B {}
class B {}
B a = new A();
}
}
错误:
Error:(10, 25) java: cannot find symbol
symbol: class B
location: class com.test.T
Error:(12, 15) java: incompatible types
required: B
found: A
在声明这些类时,顺序真的重要吗?
解决方法:
是的,这对当地的课程很重要.值得注意的是,本地课程在实际代码中非常罕见.我只记得曾经使用过一次.但是,为了感兴趣……
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.
现在“休息”并不十分清楚,但我认为这意味着“从这一点开始”.所以基本上B不在A的声明范围内,因此错误.
为了增加乐趣,在声明B之前,您可以引用另一种称为B的类型:
public class T {
public static void main(String[] args) {
class A extends B {}
class B {}
B a = new A();
}
}
class B {}
得到:
error: incompatible types: A cannot be converted to B
标签:java
来源: https://codeday.me/bug/20190724/1527006.html