java - 重载 Java 函数并确定执行哪一个

标签 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(String[] args) {
        short number = (short) 5;
        System.out.println(numberTest(number, 3));
    }

}

我已经对此进行了测试 - Java 使用第一个 numberTest() 函数。为什么?为什么它不使用第二个,或者更确切地说,为什么它不显示编译器错误?

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

最佳答案

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 中的整数文字始终为 intlong。作为一个简单的例子,这段代码:

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

来自section 3.10.1 of the JLS :

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/

相关文章:

java - 如何使用我的 Java/Android 应用程序进行 SSH?

java.lang.IllegalArgumentException : Service not registered: com. google.android.gms.internal.measurement.zziy@11da9cb2

python - 使用python在azure函数中进行更新的rest api

c - 如何在 C 中声明一个条目数量未知的数组?

overloading - 我怎样才能近似方法重载?

C++输入重载陷入while循环

java - 频繁调用 java.lang.Runtime 的totalMemory()/freeMemory() 对性能有何影响?

java - 如果我没有告诉它,为什么我的代码会显示提示两次?

javascript - 如何使用一个 Javascript 函数将数组中多张图片的大小加倍

java - 重写方法中的泛型