java - 在 Java 中声明类时顺序重要吗?

标签 java

为什么这段代码甚至不能编译?

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/

相关文章:

java - JDBC 中的问号占位符和 c3p0 PreparedStatement 未在 setString() 中被替换

java - 使用Spring框架提供的StoredProcedure调用Oracle存储过程

java - JPA xml 映射找不到字段

java - 错误 : Execution failed for task ':app:mergeDebugJavaResource'

java - HAPI FHIR 检索患者

java - 使用 StepExecutionContext/JobExecutionContext 共享大值 Hashmap 的后果

java - 在java中导入文件

java - 迭代器删除与 ArrayList 删除之间的区别?

java mongodb 3.0 : find value in internal array of documents

java - 确定一周中的哪一天是一个月中的每个日期