Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When using overloading with type promotion, why method calling is ambiguous?

Tags:

java

public class aman {
    void m(double a , int b, int c) {
        System.out.println("second");
    }
    void m(float a , int b, double c) {
        System.out.println("first");
    }
    public static void main(String[] args) {
        aman obj = new aman();
        obj.m(23, 12, 1);
    }
}

Here, method m() has been overloaded but i am not understanding why the call is ambigous because in first method only 1 conversion needs to take place whereas in second method, two conversions are required. So, definitely first method should have been called. Please give the reason why this is not happening or if i am missing some rule.

like image 428
Aman Avatar asked Apr 10 '14 14:04

Aman


2 Answers

The JLS will not consider 2 conversions and 1 conversion to be a difference. It will only distinguish between having-to-convert and not-having-to-convert.

Since both methods have-to-convert, they are equally possible.

Related to this subject, there is my answer on a similar question (but not entirely the same).

like image 170
Jeroen Vannevel Avatar answered Oct 04 '22 14:10

Jeroen Vannevel


here , method will be ambiguous becs you are filling all parameters as integer values, then the compiler will confuse (for automatic type cast). thus you need to define something like this suffix for your code:

public class aman {
    void m(double a , int b, int c) {
        System.out.println("second");
    }
    void m(float a , int b, double c) {
        System.out.println("first");
    }
    public static void main(String[] args) {
        aman obj = new aman();

        obj.m(20d, 30, 40);//for calling first method 
        obj.m(23f, 12, 1d);//for calling second method.
    }
}
like image 20
Raju Sharma Avatar answered Oct 04 '22 14:10

Raju Sharma