为什么这段代码甚至不能编译?
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
声明此类类时顺序真的很重要吗?
最佳答案
是的,对于本地类(class)很重要。值得注意的是,本地类在实际代码中难以置信地很少见。我只记得曾经用过一次。但是,为了兴趣...
来自 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.
现在“休息”不是很清楚,但我相信它的意思是“从现在开始”。所以基本上 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 - 在 Java 中声明类时顺序重要吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32254424/