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 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 .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.