Do we need forward declarations in Java?
Last Updated :
22 Mar, 2017
Predict output of the following Java program.
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);
}
}
|
Output:
fun() called: x = 5
The Java program compiles and runs fine. Note that Test1 and fun() are not declared before their use. Unlike C++, we don’t need forward declarations in Java. Identifiers (class and method names) are recognized automatically from source files. Similarly, library methods are directly read from the libraries, and there is no need to create header files with declarations. Java uses naming scheme where package and public class names must follow directory and file names respectively. This naming scheme allows Java compiler to locate library files.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...