2

I'm currently reviewing for OCA exam and thought int/float method would work on the third test.

In OCA Study Guide of Jeane Boyarsky only says 4 order rules to choose the right overloaded method.

  1. Exact match by type
  2. Larger primitive type
  3. Autoboxed type
  4. Varargs

Can someone explain why java says it's ambiguous?

public static void main(String... args){
    OverLoadingMethod ov=new OverLoadingMethod();
    ov.test(1F,2);
    ov.test(1,2F);
    ov.test(1,2);
}
public void test(float i,int j){
    System.out.println("float/int");        
}

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

Produces this error

OverLoadingMethod.java:12: error: reference to test is ambiguous
        ov.test(1,2);
          ^
  both method test(float,int) in OverLoadingMethod and method test(int,float) in OverLoadingMethod match
8
  • which method do you think it should call? Why? Commented Oct 1, 2018 at 6:45
  • I thought it should call test(int,float) though test(float,int) would work. compiler should prioritize the first valid parameter which is int. then convert the second parameter to float by Rule #2 Commented Oct 1, 2018 at 6:46
  • compiler should prioritize the first valid parameter - where is that stated? Commented Oct 1, 2018 at 6:47
  • @Javajansen "compiler should" who says it should? Commented Oct 1, 2018 at 6:48
  • It's just my thought. that's how my brain will work if I'm a compiler. Commented Oct 1, 2018 at 6:48

3 Answers 3

4

None of the overloads take two ints.

So, one of the ints has to be widened to a float. But which one? An overload exists where the float is the first parameter, and another overload exists where the float is the second.

Which should be picked? Which is objectively better? Neither is, according to the rules the language spec. Hence ambiguous.

Sign up to request clarification or add additional context in comments.

Comments

0

Java automatically casts int into float since there is no loss of precision.

Thus your test(1,2) can be interpreted as two float arguments, one float - one int, and one int - one float also. Thus it's ambiguous for the compiler.

Comments

0

For ov.test(1,2), both test(int i,float j) and test(float i,int j) are accessible and applicable. Then the compiler needs to choose the most specific one, while any of them is not specific enough, so compiler error happens.

The whole complete choosing procedure is descirbed in java language specification 15.12.2.5. Choosing the Most Specific Method

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.