Why is a method available in Java before its declaration?

Auro :

I was going through the concept of hoisting in JavaScript where all function and variable declarations are hoisted before any execution takes place and this is the reason why a function is available before its actual declaration part.

Got me wondering how exactly it worked in Java.

Consider the following code:

package declarationOrder;

public class Main {

    int num = init();

    int init() {
        return 5;
    }
}

How exactly is the method init() available for a call before its declaration part is reached?

Consider the other example:

package declarationOrder;

public class Main {

    int num1 = num2; // compiler error
    int num2 = 5;
}

How is it that the order of declaration of the variables plays a role here?

Why and how is the method treated differently?

YCF_L :

The compiler follow an order to load contents(attributes, methods, static blocks, ..) in class in Java :

In your case the method is the first one which are loaded, then the class attributes.

about the attributes it will be loaded in order of initialization, you get an error in the second example because num2 is mentioned before num1 if you inverse the order it will work fine :

int num2 = 5;
int num1 = num2;

For more details take a look at 12.4.2. Detailed Initialization Procedure

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=90041&siteId=1