Computer Applications

What is an ambiguous invocation? Give an example.

User Defined Methods

15 Likes

Answer

Sometimes there are two or more possible matches in the invocation of an overloaded method. In such cases, the compiler cannot determine the most specific match. This is referred to as ambiguous invocation. It causes a compile time error. For example, the below program will cause a compile time error due to ambiguous invocation:

public class AmbiguousDemo {

    public static double max(double num1, int num2) {
        if (num1 > num2)
            return num1;
        else
            return num2;
    }

    public static double max(int num1, double num2) {
        if (num1 > num2)
            return num1;
        else
            return num2;
    }

    public static void main(String args[]) {
        /*
         * This line will cause a compile time error
         * as reference to max is ambiguous
         */
        System.out.println(max(19, 20));
    }
}

Answered By

9 Likes


Related Questions