I'm doing an assignment in java about overloading, overriding and interfaces. One of the parts requires me to create overloading methods, with short, int, float and double. The methods only need to sum the numbers, easy enough.
Here is where I'm stuck:
public short sum(short x, short y)
{
System.out.println("I'm method on line 10");
return x+y;
}
I have this method, eclipse kept flagging by suggesting I do a (int) type cast. If I did that, it would defeat the purpose of this assignment. So after doing some googling, I wrote this:
public short sum(short x, short y)
{
System.out.println("I'm method on line 10");
short t = (short)(x+y);
return t;
}
In my main method, I created an object:
public static void main(String[] args)
{
OverloadingSum obj1 = new OverloadingSum();
System.out.println(obj1.sum(3,3));
}
So, when I run this it'll tell me that it used the int sum(int x, int y) method for the values (3,3) and not the short sum method i want it to use. My question is what numbers can I test so that the short method is called and not the int method.
To do this, you can explicitly cast the parameters to short
s to force the short
method to be called.
For example, change:
System.out.println(obj1.sum(3,3));
to:
System.out.println(obj1.sum((short) 3,(short) 3));