加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 重载方法如何工作?

发布时间:2020-12-14 16:17:12 所属栏目:Java 来源:网络整理
导读: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
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方法.

直接从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 type方法的重载方法被调用.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读