重载Java函数并确定执行哪个函数
说到重载函数,我还没有完全理解Java如何决定在运行时执行哪个函数。假设我们有一个这样的简单程序:重载Java函数并确定执行哪个函数,java,function,overloading,Java,Function,Overloading,说到重载函数,我还没有完全理解Java如何决定在运行时执行哪个函数。假设我们有一个这样的简单程序: public class Test { public static int numberTest(short x, int y) { // ... } public static int numberTest(short x, short y) { // ... } public static void main(Stri
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));
}
}
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
我已经对此进行了测试,Java使用了first numberTest()函数。为什么?为什么不使用第二个,或者更确切地说,为什么不显示编译器错误
第一个参数是short
,可以。但第二种方法区分了这两种功能。由于函数调用只使用了3
,所以可能两者都有,不是吗?而且不需要类型转换。或者每当我使用“3”作为int
时,Java是否应用类型转换?它总是以byte
开头,然后转换成short
和int
第一个参数很短,好的。但第二种方法区分了这两种功能。因为函数调用只使用了3个,所以可能是两个,不是吗
不可以。Java中的整数文本总是int
或long
。作为一个简单的示例,以下代码:
static void foo(short x) {
}
...
foo(3);
给出如下错误:
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));
}
}
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
发件人:
如果整型文字以ASCII字母L或L(ell)作为后缀,则其类型为long;否则为int型(§4.2.1)
除非另有说明,否则文字
3
将自动被视为int
。
您可以在这里找到更多信息:文本
3
是一个int
值。因此,第一个版本是方法调用的最佳匹配。