Reputation: 815
I have a short program to test overload method in java. This is my code:
public static void main(String[] args) {
// TODO code application logic here
// Case 1
f2(5);
// Case 2
char x = 'a';
f2(x);
// Case 3
byte y = 0;
f2(y);
// Case 4
float z = 0;
f2(z);
}
And there are my methods :
public static void prt(String s) {
System.err.println(s);
}
public static void f2(short x) {
prt("f3(short)");
}
public static void f2(int x) {
prt("f3(int)");
}
public static void f2(long x) {
prt("f5(long)");
}
public static void f2(float x) {
prt("f5(float)");
}
and this is result:
f3(int)
f3(int)
f3(short)
f5(float)
I can't understand how does it running with case 2 and 3. Any explain for me ?
Upvotes: 0
Views: 1129
Reputation: 213223
Method invocation in case of overloaded methods will invoke the most specific method based on the type parameters, and the actual type you pass.
Method invocation conversion follows the following path:
some more are there, not applicable here though. See JLS 5.3 for Method Invocation Conversion.
So, for f2(x);
as there is no exact match for char
type, so the method f2(int)
is invoked, as the most specific type to which char
can be converted by widening conversion is int
. No, char
to short
is not a widening conversion.
Similary, for f2(y)
, there is no exact match for byte
type, so the method f2(short)
is invoked, as short
is the most specific type that byte
can be widened to.
See JLS 5.1.2 for Widening Primitive conversions:
19 specific conversions on primitive types are called the widening primitive conversions:
byte
toshort
,int
,long
,float
, ordouble
short
toint
,long
,float
, ordouble
char
toint
,long
,float
, ordouble
Upvotes: 2