How javac detect ambiguity?

35 Views Asked by At

How javac (java compiler) finds the errors in respect to ambiguity and generates errors in compile time itself ?

how the compiler finds that we are passing a null value before execution

public class Ambiguity {

 public static void main(String[] args) {
    Ambiguity test = new Ambiguity();
    test.overloadedMethod(null);               

}

void overloadedMethod(IOException e) {
    System.out.println("1");
}

void overloadedMethod(FileNotFoundException e) {
    System.out.println("2");
}

void overloadedMethod(Exception e) {
    System.out.println("3");
}

void overloadedMethod(ArithmeticException e) {
    System.out.println("4");
}

}
1

There are 1 best solutions below

0
Thomas On

The point isn't that the compiler knows you're passing null; the point is that when you write a literal null in your code, the compiler doesn't know what the type of that null is, so it doesn't know which overload to call.

This, for example, would compile just fine:

    FileNotFoundException e = null;
    test.overloadedMethod(e);

You can also use an explicit cast to indicate which type you intended:

    test.overloadedMethod((FileNotFoundException) null);

Keep in mind that overloading is resolved at compile time. So if you're calling test.overloadedMethod(e) where e is statically of type Exception, it will always call overloadedMethod(Exception) even if e is a FileNotFoundException at runtime.