【问题标题】:How do overloaded methods work?重载方法如何工作?
【发布时间】:2013-10-08 09:18:34
【问题描述】:
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 类型参数的方法?

【问题讨论】:

标签: java overloading


【解决方案1】:

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

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

直接来自JLS-15.12.2.5

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

正如 BMT 和 LastFreeNickName 正确建议的那样,(Object)null 将导致调用 Object 类型方法的重载方法。

【讨论】:

  • 但是对于null,String和Object都处于同一级别,那么String怎么能更具体呢?
  • 完全正确!您可以尝试将 (Object)null 作为参数传递,它会选择其他方法。
  • 当它在你的代码中遇到一个字符串文字时,编译器会创建一个带有它的值的String object——在这种情况下,Null
  • @BMT 嗯? null 不是任何字符串文字的值(尽管 "null" 可能是),并且无论如何在 OP 的代码中都没有字符串文字。你在说什么?
【解决方案2】:

添加到现有回复中,我不确定这是否是因为自问题以来的 Java 版本较新,但是当我尝试使用将整数作为参数而不是对象的方法编译代码时,代码仍然编译。但是,以 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 被归类为字符串对象。

回到所问的问题,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。 Integer 和 Boolean 类型转换为 int 和 boolean 类型的对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-05
    • 1970-01-01
    相关资源
    最近更新 更多