简体   繁体   English

Java方法调用重载逻辑

[英]Java method call overloading logic

For the following code why does it print A, B? 对于以下代码,为什么要打印A,B? I would expect it to print B, B. Also, does the method call performed by the JVM is evaluated dynamically or statically? 我希望它能打印B,B。另外,JVM执行的方法调用是动态还是静态评估的?

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) . 静态类型的a为A,因此第一个方法调用被解析为call(A a)

Since your object is known by its type A at that moment, the method with argument A is invoked. 由于此时对象的类型A已知,因此调用带参数A的方法。 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也是A - 但是这两种方法不能同时被调用。

B is a subclass of A . BA的子类。 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'. 由于您实例化B ,但将其分配给变量类型A ,所有B细节都将“丢失”,因此call(a)将被调度到call(A, a)并打印'A'。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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