Order of declaring methods in java

雨燕双飞 提交于 2020-07-22 09:12:05

问题


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?


回答1:


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?




回答2:


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

  }
}


来源:https://stackoverflow.com/questions/52137515/order-of-declaring-methods-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!