Java Reference
In-Depth Information
print("Hello"); // which print ?
which print method is to be invoked? While not obvious, this example
actually has clearly defined behavior: a fixed-argument method will al-
ways be selected over a varargs methodagain, see " Finding the Right
Method " on page 224 for details. So in this case it will invoke the print
method that takes a single String parameter. In contrast, this invocation
is ambiguous and results in a compile-time error:
print("Hello", "World"); // INVALID: ambiguous invocation
This could be a string and a one-element sequence, or a two-element
sequence. The only way to resolve this ambiguity is to pass actual arrays
if you intend to match with the sequence parameters:
print("Hello", new String[] {"World"});
print( new String[] { "Hello", "World" });
The first invocation now clearly matches the two-parameter print meth-
od, and the second clearly matches the single-sequence-parameter
print method.
You can best avoid such situations by never overloading methods in a
way that leads to such ambiguity.
Exercise 2.17 : Add two turn methods to Vehicle : one that takes a num-
ber of degrees to turn and one that takes either of the constants Ve-
hicle.TURN_LEFT or Vehicle.TURN_RIGHT .
 
Search WWH ::




Custom Search