📜  我们需要Java中的前向声明吗?

📅  最后修改于: 2020-02-12 16:26:33             🧑  作者: Mango

预测以下Java程序的输出。

// 文件名: Test2.java
// 函数使用Test1,这个类在之后会声明
class Test2 {
    public static void main(String[] args) {
         Test1 t1 = new Test1();
         t1.fun(5);
    }
}
class Test1 {
    void fun(int x) {
        System.out.println("fun() called: x = " + x);
    }
}

输出:

fun() called: x = 5

Java程序可以编译并正常运行。注意,Test1fun()在使用前未声明。与C++不同,我们不需要 Java中的前向声明。标识符(类和方法名称)是从源文件中自动识别的。同样,直接从库中读取库方法,无需创建带有声明的头文件。Java使用命名方案,其中程序包和公共类名称必须分别跟随目录和文件名。这种命名方案允许Java编译器定位库文件。