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.println("Inside Object Method");
}
}
当我尝试运行给定的代码时,我得到以下输出:
任何人都可以解释为什么使用String类型参数的方法被调用? 解决方法最重要的方法选择最具体的方法参数在这种情况下,String是Object的子类.因此String变得比Object更具体.因此,打印了Inside String方法. 直接从JLS-15.12.2.5
正如BMT和LastFreeNickName正确提示的那样,(Object)null将引起使用Object type方法的重载方法被调用. (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
