1

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.

user207421
  • 305,947
  • 44
  • 307
  • 483
Naman
  • 237
  • 2
  • 4
  • 10
  • use `Short.valueOf("3")` for example (but using short is usually a bad idea) –  Nov 18 '15 at 06:33
  • 2
    @RC. No and no. You don't need to use a string literal, it is just wasteful, and this is not a question about instantiating `Short` objects. – user207421 Nov 18 '15 at 06:36

4 Answers4

4

To do this, you can explicitly cast the parameters to shorts 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));
Jonathan Lam
  • 16,831
  • 17
  • 68
  • 94
1
obj1.sum(3,3)

You need to either cast the values:

obj1.sum((short)3,(short)3)

or use variables:

short v1 = 3;
short v2 = 3;
// ...
... obj1.sum(v1,v2)...
user207421
  • 305,947
  • 44
  • 307
  • 483
0

type casting is required while passing arguments, use:

public static void main(String[] args) 
{
OverloadingSum obj1 = new OverloadingSum();     
System.out.println(obj1.sum((short)3,(short)3));
}

Integer literals implicitly have the type int, and converting from an int to byte or short potentially loses information, so it requires explicit casting.

amit dayama
  • 3,246
  • 2
  • 17
  • 28
0

You can try something like this

public static void main(String[] args) {
        short x=3;
        short y=3;
        addShort(x,y);

    }

    public static void addShort(short a,short b)
    {
        short c=(short)(a+b);

    }

Other than this,you need to explicitly cast while passing them like this

addShort((short) 3,(short)3);
RockAndRoll
  • 2,247
  • 2
  • 16
  • 35