JAVA Object / String方法重载 [英] JAVA Object/String method overload

查看:578
本文介绍了JAVA Object / String方法重载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出于好奇我试过这个例子。

Just out of curiosity I tried this example.

public class Class1 {

    public void method(Object obj){
        System.out.println("Object");
    }

    public void method(String str){
        System.out.println("String");
    }

    public static void main(String... arg){
        new Class1().method(null);
    }

}

输出为字符串。我想知道JVM决定以什么为基础调用String作为参数而不是Object的方法。

The output being "String". I want to know on what basis the JVM decides to invoke method taking String as argument and not Object.

推荐答案

每当不止一个重载方法可以应用于参数列表,使用最具体的方法。

Whenever more than one overloaded methods can be applied to the argument list, the most specific method is used.

在这种情况下,传递 null 时可以调用其中一个方法,因为null type是可分配的到对象字符串 String 的方法更具体,因此将被选中。

In this case either of the methods can be called when passing null, since the "null type" is assignable to both Object and to String. The method that takes String is more specific so it will be picked.

这篇关于JAVA Object / String方法重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆