Do we need forward declarations in Java?


Forward declarations means the declaration of a method or variable prior to its implementation. Such declaration is necessary in C/C++ programming language in order to be able to use a variable or object before its implementation. In case, if we want to use a library code, then we need to create its header file and use it. But this is not a case in Java.

  • Java allows using a variable, class prior to its declaration and implementation.

  • Java allows using libraries code without any need of header files.

Following example showcases the same. Here we have used a class object before its declaration.

Example

public class Tester{
   public static void main(String args[]) {
      Test t = new Test();
      t.display();
   }
}
class Test {
   public void display() {
      System.out.println("Test");
   }
}

Output

Test

Updated on: 21-Jun-2020

423 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements