The book I am reading on Java states something confusing and unacceptable.
Learning About Ambiguity
When you overload methods, you risk creating an ambiguous situation - one which the compiler cannot determine which method to use. For example, consider the following overloaded
computeBalance()
method declarations:public static void computeBalance(double deposit) public static void computeBalance(double withdrawal)
If you declare a
double
variable namedmyDeposit
and make a method call such ascomputeBalance(myDeposit);
, you will have created an ambiguous situation. Both methods are exact matches for your call. You might argue that a call using a variable namedmyDeposit
"seems" like it should go to the version of the method with the parameter nameddeposit
, but Java makes no assumptions based on variable names. Each version ofcomputeBalance()
could accept adouble
, and Java does not presume which one you intend to use.
This violates the rules for overloading a method. How can a method be overloaded with the same parameter list? Isn't it impossible or am I not getting something? I have tried and compiled such a code, it returns the following error (which makes sense):
method computeBalance() is already defined in class XXX