-2

For the below code, I do understand that it makes sense to be ambiguous for the calling method to know which overloaded method to call however I am unable to understand how exactly the parameter matching is checked here.

public class Test{
    public void m1(float i,int j){
        System.out.println("float method ");
    }

    public void m1(int i, float j){
        System.out.println("int method ");
    }

    public static void main(String[] args) {
        Test a=new Test();
        a.m1(10,10); // The method m1(float, int) is ambiguous for the type Test
    }
}
Ajeet
  • 68
  • 1
  • 9

2 Answers2

5

Use should make one of the arguments explicitly float, i.e. use either a.m1(10f, 10);or a.m1(10, 10f); Otherwise compiler cannot realize which method to invoke

Vladimir Vagaytsev
  • 2,871
  • 9
  • 33
  • 36
  • yes i do agree with your answer but my doubt is why its not getting auto promoted. I mean when we have method m1(float i) and we call the method by passing m(10) it will execute perfectly, we are not required to call method as m(10f) then why not in above case! – Ajeet Jun 09 '16 at 14:33
  • 1
    @Ajeet because there is only one choice. – Murat Karagöz Jun 09 '16 at 14:34
  • 1
    It cannot be autopromoted, because there is no unambiguous way to choose between 2 methods. If you pass `(10, 10)`, how can compiler decide what argument should be casted to float? `10` is an integer value in Java. See the answer posted by @dShringi below – Vladimir Vagaytsev Jun 09 '16 at 14:36
3

If more than one member method is both accessible and applicable to a method invocation the Java programming language uses the rule that the most specific method is chosen. So here java compiler doesn’t consider any of them to be more specific, hence the error.

For the detailed understanding, please read JLS.

dShringi
  • 1,497
  • 2
  • 22
  • 36