Do we need forward declarations in Java?
Predict output of the following Java program.
// filename: Test2.java // main() function of this class uses Test1 which is declared later in // this file 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); } } |
chevron_right
filter_none
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.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Recommended Posts:
- Java.util.BitSet class methods in Java with Examples | Set 2
- Shadowing of static functions in Java
- How does default virtual behavior differ in C++ and Java ?
- How are Java objects stored in memory?
- How are parameters passed in Java?
- Are static local variables allowed in Java?
- final variables in Java
- Default constructor in Java
- Assigning values to static final variables in Java
- Comparison of Exception Handling in C++ and Java
- Does Java support goto?
- Arrays in Java
- Inheritance and constructors in Java
- More restrictive access to a derived class method in Java
- Comparison of static keyword in C++ and Java



