.

Issue | Resolved - The method test(Object) is ambiguous for the type Master

Question:

1. Is this code correct?
2. If not, what type of error will it throw - run-time or compile-time?
3. What is the reason behind that?


public class Master {

    public static void test(Object a) {
        System.out.println("Object");
    }

    public static void test(String s) {
        System.out.println("String");
    }
   
    public static void test(Integer i) {
        System.out.println("Integer");
    }
   
       
    public static void main(String[] args) {
        System.out.println("main");
        test(null);
    }
}


Answer:

1. No.

2. Compile-time error

3. Since there are three methods with arguments as Object, String and Integer. Java choose more specific data type first. But still it won't be able to figure out whether that argument is passed for String or Integer(which are more specific than Object).
Therefore, you'll see compile time error that it has ambiguous methods.

No comments :

Post a Comment

Recent Posts