ICSE Class 10 Computer Applications Question 10 of 43

User-Defined Methods — Question 10

Back to all questions
10
Question

Question 10

What is an ambiguous invocation? Give an example.

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));
    }
}