Java Methods – Resolving Ambiguity in Method Overloading

ambiguityjavamethods

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 named myDeposit and make a method call such as computeBalance(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 named myDeposit "seems" like it should go to the version of the method with the parameter named deposit, but Java makes no assumptions based on variable names. Each version of computeBalance() could accept a double, 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

Best Answer

I agree with your assessment that this is poor, wrong and/or misleading text.

As you have pointed out, the compiler will complain based on these declarations alone: no call to computeBalance is required. These declarations taken together are in error, there is no (legal) overloading going on here.

The idea from the text that

You might argue that a call using a variable named myDeposit seems like it should go to the version of the method with the parameter named deposit ...

is an odd suggestion to say the least. The author appears to be evoking a hypothetical situation (variable name matching (to resolve erroneously declared overloads)) that isn't very apropos of how these languages work, but then goes on to say they don't work like that. Silly if you ask me.

For what it's worth, there are much better examples of ambiguous overloads that could be presented.

Two methods with the same name each taking one parameter of a different (class) type. Then you call that method name passing null. The compiler will not know which of the overloads to invoke: you'd have to cast null to one of those types.