2

关于重载函数,我还没有完全理解 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() 函数。为什么?为什么不使用第二个,或者更确切地说,为什么不显示编译器错误?

第一个参数是short,好吧。但第二个区分这两个功能。由于函数调用使用 just 3,它可以是两者,不是吗?并且不需要类型转换。或者,每当我使用“3”作为时,Java 是否会应用类型转换int?它总是以byte然后转换为short然后int吗?

4

2 回答 2

6

第一个参数很短,好吧。但第二个区分这两个功能。由于函数调用仅使用 3,它可能是两者,不是吗?

不,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

JLS 的第 3.10.1 节

如果整数文字以 ASCII 字母 L 或 l (ell) 为后缀,则它是 long 类型;否则它是 int 类型(§4.2.1)。

于 2012-11-22T21:02:50.360 回答
3

除非另有说明,否则该文字3将自动被视为一个。int您可以在此处找到更多信息:http: //docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

于 2012-11-22T21:02:55.990 回答