Java overload overload

java cannot call any overload method as shown below: -

class LspTest{ public void add(int a, float b){ System.out.println("First add"); } public void add(float a, int b){ System.out.println("second add"); } public static void main(String [] a){ LspTest test = new LspTest(); test.add(1,1); } } 

Please explain that I am confused about this.

+2
java overloading
source share
4 answers

In your methods, you have (int, float) and (float, int) parameters, but when you call the method, you pass int (1,1) values. Java-complier can automatically type float in int if necessary. But in this case, the compiler cannot solve the automatic cast type, which int floats. Therefore, it shows ambiguity.

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

PS To specify a value for float, you can write f with it.

+3
source share

When you initialize literal values, in this case the compiler will not be able to deduce the exact type. Therefore, he does not know which overload causes and returns an error that the link to add ambiguous. You can fix this by adding arguments to the appropriate type or even better by creating typed local variables initialized with 1 and passing the variables as parameters, for example:

 int a = 1; float b = 1; LspTest test = new LspTest(); test.add(a,b); 
+2
source share

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

+2
source share

This is a clear case of ambiguity that leads to a compilation error.

The Java compiler supports type promotion. First of all, it will check for a more specific data type if it does not match, and it will facilitate the next data type.

The Java compiler will support type promotion in the following order.

byte → short → int → long → float → double

Since your parameters (int, int) can be automatically upgraded to float, the java compiler cannot decide in which case to call, since both of your methods accept (1,1)

0
source share

All Articles