Java overload confusion

后端 未结 4 1424
广开言路
广开言路 2020-12-19 14:13

java is not able to call any overload method as shown below :-

class LspTest{

    public void add(int a, float b){
    System.out.println(\"First add\");
}         


        
相关标签:
4条回答
  • 2020-12-19 14:32

    There is an ambiguity here, and the Java compiler cannot figure out which method to call. Use test.add((float) 1, 1) or test.add(1, (float) 1) to explicitly tell which method you want.

    0 讨论(0)
  • 2020-12-19 14:36

    When you initialise with literal values, in this case, compiler won't be able to infer the exact type. Therefore, it does not know which overload to call and returns the error that the reference to add is ambiguous. You can fix this by casting the arguments to the appropriate type, or even better, creating typed local variables initialised with 1 and passing the variables as parameters, like so:

    int a = 1;
    float b = 1;
    LspTest test = new LspTest();
    test.add(a,b);
    
    0 讨论(0)
  • 2020-12-19 14:52

    In your methods you are having parameters (int, float) and (float, int) but when calling the method you are passing both the int (1,1) values. The Java complier can auto type cast float to int whenever needed. But in this case compiler cannot decide auto type cast which int to float. Therefore it shows ambiguity.

    You need to call it test.add(1f, 1); or test.add(1,1f); i.e. specify which value is int and which value is float.

    P.S. To specify a value to be float you can write f with it.

    0 讨论(0)
  • 2020-12-19 14:56

    This is the clear case of ambiguity which leads to a Compile Error.

    Java compiler supports the type promotion. First of all, it'll checks for more specific data type if not match then it'll promote to next data type.

    Java compiler will supports the type promotion in following order.

    byte --> short --> int --> long --> float --> double

    As your parameters (int,int) can be auto-promoted to float, java compiler can't decide in which one to invoke as both of your methods accepts the (1,1)

    0 讨论(0)
提交回复
热议问题