重载Java函数并确定要执行的函数 [英] Overloading Java functions and determining which one to execute

查看:48
本文介绍了重载Java函数并确定要执行的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于重载函数,我还没有完全理解Java如何确定在运行时执行哪个函数.假设我们有一个像这样的简单程序:

When it comes to overloading functions, I have not completely understood how Java determines which function to execute on runtime. Let's assume we have a simple program like this:

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()函数.为什么?为什么不使用第二个,或者为什么不显示编译器错误?

I've tested this - and Java uses the first numberTest() function. Why? Why isn't it using the second one, or rather, why isn't it showing a compiler error?

第一个参数是 short ,好吧.但是第二个区别了这两个功能.由于该函数调用仅使用 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? And there is no type conversion needed. Or does Java apply type conversion whenever I use "3" as int? Does it always start with byte and then convert to short and int then?

推荐答案

第一个参数很短,可以.但是第二个区别了这两个功能.由于函数调用仅使用3,所以可能两者都使用吗?

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 .作为一个简单的示例,此代码:

No. Integer literals in Java are always either int or long. As a simple example, this code:

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节).

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函数并确定要执行的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆