java - 重载方法如何工作?

标签 java overloading

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 类型参数的方法吗?

最佳答案

为重载方法选择最具体的方法参数

在本例中,StringObject 的子类。因此,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/

相关文章:

关于继承和转换的 C++ 问题

java - 计算文件中与 String [ ] 中的单词匹配的单词数

没有 swing 的 Java 项目

java - 将图像保存为 PDF 但总是得到相同的图像

java - PropertyPlaceholderConfigurer 用于读取属性文件和数据库

java - 动态绑定(bind)问题

delphi - 为什么仅在将重载过程分配给局部变量后才使用重载过程时会出现 'H2219 Private symbol X declared but never used'?

c++ - 具有多个函数和多个转换运算符的重载解决方案

java - 是否可以将列表转换为 JCR 值?

syntax - Golang 的多返回重载是 map 类型独有的吗?