Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order of declaring methods in java

Tags:

java

methods

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?

like image 669
George Zorikov Avatar asked Oct 15 '25 20:10

George Zorikov


2 Answers

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?

like image 73
Nikolay Kosev Avatar answered Oct 18 '25 11:10

Nikolay Kosev


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

  }
}
like image 21
sticky_elbows Avatar answered Oct 18 '25 11:10

sticky_elbows



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!