重载方法如何工作?

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

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

在这种情况下, StringObject子类。 因此String变得比Object更具体。 因此打印Inside String method

直接来自JLS-15.12.2.5

如果多个成员方法都可访问并适用于方法调用,则必须选择一个为运行时方法调度提供描述符。 Java编程语言使用选择最具体方法的规则。

由于BMT和LastFreeNickName已正确建议, (Object)null将导致调用带有Object类型方法的重载方法。

添加到现有的回复,我不确定这是否是因为问题以来的新Java版本,但是当我尝试使用将Integer作为参数而不是Object的方法编译代码时,代码仍然做了编译。 但是,以null作为参数的调用仍然在运行时调用String参数方法。

例如,

 public void testMethod(int i){ System.out.println("Inside int Method"); } public void testMethod(String s){ System.out.println("Inside String Method"); } 

仍然会给出输出:

 Inside String Method 

当被称为:

 test1.testMethod(null); 

主要原因是因为String确实接受null作为值而int不接受。 因此null被归类为String对象。

回到问题,只有在创建新对象时才会遇到类型Object。 这是通过将null作为Object by类型转换来完成的

 test1.testMethod((Object) null); 

或者使用任何类型的对象作为原始数据类型,例如

 test1.testMethod((Integer) null); or test1.testMethod((Boolean) null); 

或者通过简单地创建一个新对象

 test1.testMethod(new Test1()); 

应当指出的是

 test1.testMethod((String) null); 

将再次调用String方法,因为这将创建String类型的对象。

也,

 test1.testMethod((int) null); and test1.testMethod((boolean) null); 

将给出编译时错误,因为boolean和int不接受null作为有效值和int!= Integer和boolean!= Boolean。 整数和布尔类型强制转换为int类型和boolean类型的对象。