Hello,
As I was reading Mala Gupta's book, I came to a page where there is an interesting discussion on a scenario where there are two valid, overloaded methods but where the compiler will get confused and then report a compile-time error in response to certain inputs.
Here are the methods.
I quote from the book: "... but an issue arises when you try to execute this method using values that can be passed to both versions of the overloaded methods. In this case, the code will fail to compile ..."
Here is the code showing the use of the methods:
Because an int literal value can be passed to a variable of type double, both methods are acceptable candidates for literal values 2 and 3, and therefore the compiler fails to decide which method to pick.
This is where I get confused when I take the above concept with me and dive further into the book to the final chapter, the chapter of exceptions. There, the writer introduces from
Java 7 API two overloaded constructors of
FileInputStream.
1. public FileInputStream(String name) throws FileNotFoundException {.....}
2. public FileInputStream(File file) throws FileNotFoundException {.....}
The writer also says that, according to the Java 7 API source code, here is the definition of the version that takes a String object as the argument:
Now, if "
name" is indeed null,
this(name != null ? new File(name) : null); evaluates to
this(null); which in turn is equivalent to invocation of
FileInputStream(null); but then both
FileInputStream(String) and
FileInputStream(File) become possible choices to be invoked with a null value. Does it not give rise to ambiguity? So, isn't there a compile-time error for that?
I do understand that eventually a FileNotFoundException is raised, but it is a separate issue which comes later. How is the ambiguity resolved before that?