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

查看:149
本文介绍了方法重载中的奇怪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(对象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(对象x)

这是因为 String 类从 Object 扩展,因此更具体到 Object 。因此,编译器决定调用该方法。请记住,编译器总是选择最具体的方法来调用。请参见第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.

但是,如果你有两个带参数的方法 - String ,以及 Integer ,那么你将获得歧义 null 的错误,因为编译器无法确定哪一个更具体,因为它们是非协变类型。

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天全站免登陆