Do we need forward declarations in Java?

Java Programming Java8Object Oriented Programming

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
raja
Published on 13-Aug-2018 15:57:37
Advertisements