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");
}
}
The point isn't that the compiler knows you're passing
null; the point is that when you write a literalnullin your code, the compiler doesn't know what the type of thatnullis, so it doesn't know which overload to call.This, for example, would compile just fine:
You can also use an explicit cast to indicate which type you intended:
Keep in mind that overloading is resolved at compile time. So if you're calling
test.overloadedMethod(e)whereeis statically of typeException, it will always calloverloadedMethod(Exception)even ifeis aFileNotFoundExceptionat runtime.