说到重载函数,我还没有完全理解Java如何确定在运行时执行哪个函数。假设我们有一个像这样的简单程序:
public class Test {
public static int numberTest(short x, int y) {
// ...
}
public static int numberTest(short x, short y) {
// ...
}
public static void main(String[] args) {
short number = (short) 5;
System.out.println(numberTest(number, 3));
}
}
我已经对此进行了测试 - Java 使用第一个 numberTest() 函数。为什么?为什么它不使用第二个,或者更确切地说,为什么它不显示编译器错误?
第一个参数是短
,好的。但第二个区分了这两个功能。由于函数调用仅使用 3
,因此两者都可以,不是吗?并且不需要类型转换。或者每当我使用“3”作为 int
时,Java 是否会应用类型转换?它总是以 byte
开头,然后转换为 short
和 int
吗?
最佳答案
First parameter is short, okay. But second one distinguishes the two functions. As the function call uses just 3, it could be both, couldn't it?
没有。 Java 中的整数文字始终为 int
或 long
。作为一个简单的例子,这段代码:
static void foo(short x) {
}
...
foo(3);
出现这样的错误:
Test.java:3: error: method foo in class Test cannot be applied to given types;
foo(3);
^
required: short
found: int
reason: actual argument int cannot be converted to short by method invocation
conversion
1 error
An integer literal is of type long if it is suffixed with an ASCII letter L or l (ell); otherwise it is of type int (§4.2.1).
关于java - 重载 Java 函数并确定执行哪一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13519914/