用"null"调用重载函数.参考 [英] Calling overloaded functions with "null" reference

查看:97
本文介绍了用"null"调用重载函数.参考的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我具有以下重载函数

Let us say I have following overloaded functions

public class Test {

    public static void funOne(String s){
        System.out.print("String function");
    }

    public static void funOne(Object o){
        System.out.print("Object function");
    }

    public static void main(String[] args) {            
        funOne(null);
    }
}

为什么funOne(null)调用带有String参数签名的方法?在这里重载的优先顺序是什么?

Why would funOne(null) call the method with String argument signature? what is the precedence for overloading here?

推荐答案

在这种情况下,类层次结构中较低的类将具有优先权.换句话说,更具体的类类型在本例中为String,因为String从技术上扩展了Object.

The class that is lower in the class hierarchy will have precedence in this case. In other words the more specific class type, which would be String in this case because String extends Object technically.

如果您具有以下条件

public class A {
    ...
}

public class B extends A {
    ...
}

然后,当您定义如下所示的重载方法时:

Then when you define overloading methods like the following:

public void test(A object) {
    ...
}

public void test(B object) {
    ...
}

然后调用test(null)将调用第二个方法,因为B在类层次结构中较低.

Then calling test(null) will call the second method because B is lower in the class hierarchy.

这篇关于用"null"调用重载函数.参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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