function overloading: call to short method calls int method
Hi all,
I have a doubt regarding function overloading. I have three functions which has arguments as short, int and long. A function call to short, calls the method with the int argument. why does it happen?
Code:
public class longshort
{
public static void go(Long n){System.out.println("Long ");}
public static void go(Short n){System.out.println("Short ");}
public static void go(int n){System.out.println("int ");}
public static void main(String args[])
{
short y=6;
long z=7;
go(y);
go(z);
}
}
I am not able to clearly understand. I am passing short as the argument. Then why the function for int get invoked. Can you please tell me the conditions in which these type casts will take place. Which type will be casted to which type?
I think the reason is this. The 'short' type is a 16-bit signed two's complement integer.The java compiler acts short value as a integer type unless you are explicitly specified (Higher order).
In your class , the 'go' method have no argument that receive a parameter of type short. You have given Short wrapper class instead.
If you changed to short
public static void go(short n){System.out.println("Short ");} It will work fine.
else it will read
public static void go(int n){System.out.println("int ");}.
But if you comment the above 'int' method then it will invoke the 'Short' method.
This case is applicable for 'byte' type also.
So short and byte are having this behaviour.
You will get more information by looking Java Primitives variables.
Regards,
Jithesh
Bookmarks