Java方法调用重载逻辑 [英] Java method call overloading logic
本文介绍了Java方法调用重载逻辑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
对于以下代码,为什么要打印A,B?我希望它打印B,B。
此外,JVM执行的方法调用是动态还是静态评估?
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.
静态类型 a
是A,因此第一个方法调用被解析为 call(A a)
。
The static type of a
is A, so the first method call is resolved to call(A a)
.
这篇关于Java方法调用重载逻辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文