java 编译器 "most specific method calling rule" 是如何工作的?
How does java compiler "most specific method calling rule" work?
我无法理解 java "Choosing the Most Specific Method" 规则在函数重载中的工作原理。
我有一个 class 实现了函数重载。有两个同名函数"show"。一次接受对象类型参数,其他接受字符串类型。
我正在调用传递 null 的函数。调用带有 String 类型参数的方法。
class Test
{
public void show(String s)
{
System.out.println("hi");
}
public void show(Object o)
{
System.out.println("hello");
}
public static void main(String s[])
{
Test t = new Test();
t.show(null);
}
}
输出将是 "Hi"。请帮助我理解解释。
Java 将始终尝试使用可用方法的最具体版本。
两种方法
public void show(Object o) { ... }
public void show(String s) { ... }
可以将 null
作为有效值。在这种情况下,使用带有 String
参数的重载,因为 String
比 Object
.
更具体
如果添加第三种方法
public void show(Integer t) { ... }
您的代码将无法再编译,因为 String
和 Integer
不相关。两者都不比另一个更具体,编译无法决定使用哪个。
请参阅Java language specification。由于 String 比 Object 更 "narrow" 类型,因为它是子类型,所以将选择此方法,因为它更 "specific".
我无法理解 java "Choosing the Most Specific Method" 规则在函数重载中的工作原理。
我有一个 class 实现了函数重载。有两个同名函数"show"。一次接受对象类型参数,其他接受字符串类型。
我正在调用传递 null 的函数。调用带有 String 类型参数的方法。
class Test
{
public void show(String s)
{
System.out.println("hi");
}
public void show(Object o)
{
System.out.println("hello");
}
public static void main(String s[])
{
Test t = new Test();
t.show(null);
}
}
输出将是 "Hi"。请帮助我理解解释。
Java 将始终尝试使用可用方法的最具体版本。
两种方法
public void show(Object o) { ... }
public void show(String s) { ... }
可以将 null
作为有效值。在这种情况下,使用带有 String
参数的重载,因为 String
比 Object
.
如果添加第三种方法
public void show(Integer t) { ... }
您的代码将无法再编译,因为 String
和 Integer
不相关。两者都不比另一个更具体,编译无法决定使用哪个。
请参阅Java language specification。由于 String 比 Object 更 "narrow" 类型,因为它是子类型,所以将选择此方法,因为它更 "specific".