Gpar
Gpar

Reputation: 181

Overloading methods

I saw below question posted on this site.

"What happens when we pass int arguments to the overloading method having float as a parameter for one method and another having double param".

I thought I understood the concept and wrote this code:

public  class TestClass {

    public static void main(String args[])
    {

        TestClass t=new TestClass();

        t.sum(1/4);
    }
    void sum(double d)
    {
        System.out.println("Double==="+d);
    }
    void sum(int i)
    {
        System.out.println("Integer==="+i);
    }
    void sum(short s)
    {
        System.out.println("Short==="+d);
    }
}

According to my understanding explained on this site (as mentioned above), I thought it will print Short===0, but to my surprise it prints Integer===0. Can any one explain this to me?

Upvotes: 1

Views: 108

Answers (3)

Konstantin Yovkov
Konstantin Yovkov

Reputation: 62854

If you don't explicitly tell the compiler what are the types of 1 and 4, it assumes they are of type int. Then, / operator will apply integer division and will produce another int (which will be 0.)

After that, the method with the most specific to integer parameter type will be invoked. In your case, this will be sum(int i).

If you want to invoke some of the other overloaded methods, you will have to explicitly:

  • do a cast. For example, sum((short) (1/4)); will invoke sum(short s) due to the cast.
  • point the type of the operands. For example, sum(1d/4) will invoke sum(double d), since 1d/4 will result to double

Upvotes: 0

Eran
Eran

Reputation: 393771

First of all, these are overloaded methods, not overridden methods.

1 and 4 are integers. Therefore 1/4 is an integer division, returning 0.

Therefore, the method being called is sum(int i).

sum(short s) would never be called for an int parameter, since that would require a narrowing primitive conversion (JLS 5.1.3), that may cause data loss, and is not allowed in method invocation conversion (JLS 5.3). Such a conversion can be done with an explicit cast.

If you remove the int version, sum(double d) would be called, and if you remove the double version, the code won't compile.

In order to call the short version, you must cast the parameter to short :

t.sum ((short)(1/4));

Upvotes: 4

Tarek
Tarek

Reputation: 771

For integer number, the type int is a default choice. So, although 1 and 4 can be defined as both int or short, since you did not defined anything, the compiler identified 1 and 4 as int and therefore it entered into the function for 1/4 division (0), which took the parameter int.

Upvotes: 0

Related Questions