4

In C/C++ we have to declare functions before invoking them. In Javascript there is a hoisting variables and functions. I cannot find info about Java. Is there a hoisting of methods too?

George Zorikov
  • 139
  • 1
  • 4
  • 8
  • Look at this https://www.tutorialspoint.com/java/java_methods.htm , also in Java those are called methods – bakero98 Sep 02 '18 at 13:34

2 Answers2

7

In java functions/procedures are called methods. Only difference is that function returns value. No , there is no hoisting like JS(thank god). Only requirement for variables is that you have to create them before you use them. Just like C. But methods are part of an object. So they are attached to object and you can call them above their declaration (virtual method, everything is virtual:) ). Because calling them actually involves <Class>.method() And Class is already compiled and loaded before the time are executing it. (some reflections can bypass or change this behavior tho).

Compiler is relatively free to reorder things, but for example volatile can forbid this behaviour. By the way : Are hoisting and reordering the same thing?

Nikolay Kosev
  • 124
  • 1
  • 4
1

In java there are two types of methods: instance methods and class methods. To invoke the former you need to instantiate the class, and two invoke the latter you don't. Here is an example:

public class MyClass{

  public String instanceMethod(){
    return "This is from instance method";
  }

  public static String classMethod(){
    return "This is from class method";
  }

  public static void main(String[] args){

    System.out.println(MyClass.classMethod()); //will work

    System.out.println(MyClass.instanceMethod()); //compilation error

    MyClass myInstance = new MyClass();
    System.out.println(myInstance.instanceMethod()); //will work

  }
}
sticky_elbows
  • 1,344
  • 1
  • 16
  • 30
  • 1
    You don't instantiate a class. You instantiate an object from a class. – nicomp Sep 02 '18 at 13:59
  • 1
    Which means instantiating the class by creating an object from it, because the created object will be an instance of that class. Ever heard the statement 'An abstract class cannot be instantiated' ? @nicomp – sticky_elbows Sep 02 '18 at 14:09