方法重载中的奇怪 Java null 行为 [英] Strange Java null behavior in Method Overloading

查看:25
本文介绍了方法重载中的奇怪 Java null 行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码片段:

public static void foo(Object x) {
    System.out.println("Obj");
}
public static void foo(String x) {
    System.out.println("Str");
}

如果我调用 foo(null) 为什么没有歧义?为什么程序调用foo(String x) 而不是foo(Object x)?

If I call foo(null) why is there no ambiguity? Why does the program call foo(String x) instead of foo(Object x)?

推荐答案

为什么程序调用foo(String x) 而不是foo(Object x)

那是因为String 类从Object 扩展而来,因此更特定于Object.因此,编译器决定调用该方法.请记住,Compiler 总是选择最具体的方法来调用.请参阅 第 15.12.5 节JLS

That is because String class extends from Object and hence is more specific to Object. So, compiler decides to invoke that method. Remember, Compiler always chooses the most specific method to invoke. See Section 15.12.5 of JLS

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

If more than one member method is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the most specific method is chosen.

非正式的直觉是一种方法比另一个如果可以传递第一个方法处理的任何调用到另一个没有编译时类型错误.

The informal intuition is that one method is more specific than another if any invocation handled by the first method could be passed on to the other one without a compile-time type error.

但是,如果您有两个带参数的方法 - StringInteger,那么对于 null,您会得到 ambiguity 错误,因为编译器无法决定哪一个更具体,因为它们是非协变类型.

However, if you have two methods with parameter - String, and Integer, then you would get ambiguity error for null, as compiler cannot decide which one is more specific, as they are non-covariant types.

这篇关于方法重载中的奇怪 Java null 行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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