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?
No. Integer literals in Java are always either
int
orlong
. As a simple example, this code:Gives an error like this:
From section 3.10.1 of the JLS:
The literal
3
will automatically be considered as anint
unless otherwise noted. You can find more information here: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html