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");
}
}
当我尝试运行给定的代码时,我得到以下输出:
Inside String Method
任何人都可以解释为什么调用带有 String
类型参数的方法吗?
最佳答案
为重载方法选择最具体的方法参数
在本例中,String
是Object
的子类。因此,String
变得比 Object
更具体。因此打印了Inside String method
。
直接来自JLS-15.12.2.5
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
类型方法的重载方法。
关于java - 重载方法如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29990777/