gpt4 book ai didi

java - 重载方法如何工作?

转载 作者:太空宇宙 更新时间:2023-11-04 13:54:19 24 4
gpt4 key购买 nike

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com