简体   繁体   中英

Java method call overloading logic

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

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);
    }

}

Overloading is determined statically by the compiler. Overriding is done at execution time, but that isn't a factor here.

The static type of a is A, so the first method call is resolved to call(A a) .

Since your object is known by its type A at that moment, the method with argument A is invoked. So yes, it's determined statically .

That's in order to avoid ambiguities. Your B is also an A - but both methods can't be invoked at the same time.

B is a subclass of A . Since you instanciate a B , but assign it to a variable typed A , all B specifics will be 'lost', hence call(a) will be dispatched to call(A, a) and print 'A'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM