Wednesday, July 3, 2024
HomeLanguagesJavaDo we need forward declarations in Java?

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);
    }
}


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.

Nokonwaba Nkukhwana
Experience as a skilled Java developer and proven expertise in using tools and technical developments to drive improvements throughout a entire software development life cycle. I have extensive industry and full life cycle experience in a java based environment, along with exceptional analytical, design and problem solving capabilities combined with excellent communication skills and ability to work alongside teams to define and refine new functionality. Currently working in springboot projects(microservices). Considering the fact that change is good, I am always keen to new challenges and growth to sharpen my skills.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments