Overloading Java functions and determining which o

2019-07-11 00:58发布

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));
    }

}

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?

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?

2条回答
狗以群分
2楼-- · 2019-07-11 01:14

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?

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

static void foo(short x) {
}

...
foo(3);

Gives an error like this:

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

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

查看更多
ら.Afraid
3楼-- · 2019-07-11 01:34

The literal 3 will automatically be considered as an int unless otherwise noted. You can find more information here: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

查看更多
登录 后发表回答