Method Overloading Ambiguity Problem

While going through an article about method overriding in OOP, I stumbled upon an ambiguity problem in overriding.

Here is the java code I wrote to test it:

public class OverLoadingTest {

static void testOverload(int i,double d) {
System.out.println("testOverload 1: int, double");
}

static void testOverload(double d,int i) {
System.out.println("testOverload 2: double,int");
}

public static void main(String[] args) {

testOverload(2,3.5);
testOverload(2.5,3);
testOverload(2,3); // Compilation error:  The method testOverload(int, double) is ambiguous for the type OverLoadingTest
  }
}

In the third call testOverload(2,3), there will be a compilation error, because:

First argument 2 is int, so java compiler will decide to call the method testOverload(int,double) because its first argument is int, so it is better match than .testOverload(double,int)

Second argument 3 is also int, so java compiler will decide to call the method testOverload(double,int) because its second argument is int, so it is better match than testOverload(int,double)

As compiler will not be able to decide the right overloaded version for call, compilation error occurs.

Happy Coding !

  1. Leave a comment

Leave a comment