Java Method Call Overload Logic

For the following code, why does it print A, B? I expect it to print B, B. Also, is the JVM method call dynamically or statically evaluated?

public class Main {
    class A {

    }

    class B extends A {

    }

    public void call(A a) {
        System.out.println("I'm A");
    }

    public void call(B a) {
        System.out.println("I'm B");
    }


    public static void main(String[] args) {

        Main m = new Main();
        m.runTest();
    }

    void runTest() {
        A a = new B();
        B b = new B();

        call(a);
        call(b);
    }

}
+3
source share
3 answers

Overload is determined statically by the compiler. Overrides are performed at runtime, but this is not a factor.

The static type ais A, so the first method call is allowed call(A a).

+14
source

Since your object is known by type Aat this point, the method with the argument is Acalled. So yes, it is statically defined.

. B A, .

+3

Bis a subclass A. Since you initialize B, but assign it to a variable of type A, all tags Bwill be "lost", so it call(a)will be sent to call(A, a)and type "A".

+1
source

Source: https://habr.com/ru/post/1622874/


All Articles