重载方法如何工作? [英] How do overloaded methods work?
问题描述
public class Test1 {
public static void main(String[] args) {
Test1 test1 = new Test1();
test1.testMethod(null);
}
public void testMethod(String s){
System.out.println("Inside String Method");
}
public void testMethod(Object o){
System.out.println("Inside Object Method");
}
}
当我尝试运行给定的代码时,我得到了以下输出:
When I try to run the given code, I get the following output:
内部字符串方法
Inside String Method
有人能解释为什么调用带有 String
类型参数的方法吗?
Can anyone explain why the method with the String
type parameter is getting called?
推荐答案
为重载方法选择了最具体的方法参数
在这种情况下, String
是 Object
的子类。因此 String
变得比 Object
更具体。因此打印内部字符串方法
。
In this case, String
is subclass of Object
. Hence String
becomes more specific than Object
. Hence Inside String method
is printed.
直接来自 JLS-15.12.2.5
如果多个成员方法都可访问并适用于方法调用,则必须选择一个为运行时方法调度提供描述符。 Java编程语言使用选择最具体方法的规则。
If more than one member method is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the most specific method is chosen.
正如BMT和LastFreeNickName正确建议的那样,(Object)null
将导致重载方法与 Object
类型方法被调用。
As BMT and LastFreeNickName have correctly suggested, (Object)null
will cause overloaded method with Object
type method to be called.
这篇关于重载方法如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!